Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package com.innercirclesoftware.drawabletest;
- import android.content.Context;
- import android.graphics.Outline;
- import android.graphics.Path;
- import android.graphics.Rect;
- import android.graphics.Region;
- import android.support.annotation.NonNull;
- import android.support.annotation.Nullable;
- import android.support.v7.widget.AppCompatImageButton;
- import android.util.AttributeSet;
- import android.view.MotionEvent;
- import android.view.View;
- import android.view.ViewOutlineProvider;
- public class DiamondImageButton extends AppCompatImageButton {
- @Nullable private Region clickRegion;
- public DiamondImageButton(Context context) {
- super(context);
- init();
- }
- public DiamondImageButton(Context context, AttributeSet attrs) {
- super(context, attrs);
- init();
- }
- public DiamondImageButton(Context context, AttributeSet attrs, int defStyleAttr) {
- super(context, attrs, defStyleAttr);
- init();
- }
- private void init() {
- setOutlineProvider(new ViewOutlineProvider() {
- @Override
- public void getOutline(View view, Outline outline) {
- int left = 0;
- int top = 0;
- int right = view.getWidth();
- int bottom = view.getHeight();
- int centerX = (left + right) / 2;
- int centerY = (top + bottom) / 2;
- Path path = new Path();
- path.moveTo(centerX, top);
- path.lineTo(left, centerY);
- path.lineTo(centerX, bottom);
- path.lineTo(right, centerY);
- path.close();
- setClickRegion(path);
- outline.setConvexPath(path);
- }
- });
- }
- private void setClickRegion(@NonNull Path clipPath) {
- Rect clipBounds = new Rect(0, 0, getWidth(), getHeight());
- this.clickRegion = new Region();
- this.clickRegion.setPath(clipPath, new Region(clipBounds));
- }
- @Override
- public boolean onTouchEvent(MotionEvent event) {
- int x = (int) event.getX();
- int y = (int) event.getY();
- if (clickRegion != null && !clickRegion.contains(x, y)) {
- //clicked outside the diamond
- return false;
- }
- return super.onTouchEvent(event);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement