首页 > 解决方案 > 如何制作自定义形状按钮?

问题描述

有必要点击仅在选定区域上起作用,方形按钮不适合

请帮我 在此处输入图像描述

标签: androidandroid-layoutbutton

解决方案


我找到了一个解决方案,我通过点创建一个多边形,并在检查时单击它。坐标是否在多边形中

public class CustomFormView extends View {

private ArrayList<Point> points;
public Paint paint;

public CustomFormView(Context context, ArrayList<Point> points) {
    super(context);
    paint = new Paint();

    this.points = points;
}

@Override
protected void onDraw(Canvas canvas) {
    //paint.setColor(Color.TRANSPARENT);
    paint.setStyle(Paint.Style.STROKE);

    Path path = new Path();
    path.moveTo(points.get(0).x, points.get(0).y);
    for (int i = 1; i < points.size(); i++) {
        path.lineTo(points.get(i).x, points.get(i).y);
    }
    path.close();

    canvas.drawPath(path, paint);
}

@Override
public boolean onTouchEvent(MotionEvent event) {
    if (event.getAction() == MotionEvent.ACTION_DOWN) {
        if (!contains(new Point(event.getX(), event.getY()))) {
            return false;
        }
    }
    return super.onTouchEvent(event);
}

public boolean contains(Point test) {
    int i;
    int j;
    boolean result = false;
    for (i = 0, j = points.size() - 1; i < points.size(); j = i++) {
        if ((points.get(i).y > test.y) != (points.get(j).y > test.y) &&
                (test.x < (points.get(j).x - points.get(i).x) * (test.y - points.get(i).y) / (points.get(j).y - points.get(i).y) + points.get(i).x)) {
            result = !result;
        }
    }
    return result;
}
}

推荐阅读