如何在Android中剪辑圆

时间:2018-12-11 16:38:02

标签: java android custom-view clip

我需要剪辑自定义圆圈按钮。我是由视图组完成的,因为我需要中心的图像。所以我需要使它在按钮附近按下时不起作用。这是该视图的代码:

public class CircleCustom extends ViewGroup {

private static final int Circle_RADIUS_DEF = 120;
private Paint mPaintSquare;

private int mSquareColor;
private int mSquareSize;

private int width;
private int height;

private Path path;

private ImageView mButIconImage;

public CircleCustom(Context context) {
    super(context);

    init(context);
}

public CircleCustom(Context context, AttributeSet attrs) {
    super(context, attrs);

    init(context);
}

public CircleCustom(Context context, AttributeSet attrs, int defStyleAttr) {
    super(context, attrs, defStyleAttr);

    init(context);
}


private void init(Context context) {

    mButIconImage = new ImageView(context);
    mButIconImage.setImageResource(R.drawable.ic_fitness_center_black_24dp);
    addView(mButIconImage);

    mPaintSquare = new Paint(Paint.ANTI_ALIAS_FLAG);

    mSquareColor = Color.GREEN;
    mSquareSize = Circle_RADIUS_DEF * 2;

    mPaintSquare.setColor(mSquareColor);

    path = new Path();
}


@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    width = MeasureSpec.getSize(widthMeasureSpec);
    height = MeasureSpec.getSize(heightMeasureSpec);
    widthMeasureSpec = getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec);

    measureChild(mButIconImage, widthMeasureSpec, heightMeasureSpec);

    setMeasuredDimension(mSquareSize, mSquareSize);
}


@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
    final int width = r - l;

    mButIconImage.layout(
            Circle_RADIUS_DEF - mButIconImage.getMeasuredWidth() / 2,
            Circle_RADIUS_DEF - mButIconImage.getMeasuredHeight() / 2,
            Circle_RADIUS_DEF + mButIconImage.getMeasuredWidth() - mButIconImage.getMeasuredWidth() / 2,
            Circle_RADIUS_DEF + mButIconImage.getMeasuredHeight() - mButIconImage.getMeasuredHeight() / 2
    );
}

@Override
protected void dispatchDraw(Canvas canvas) {
    canvas.drawCircle(Circle_RADIUS_DEF, Circle_RADIUS_DEF, Circle_RADIUS_DEF, mPaintSquare);

    canvas.translate(0,0);

    path.addCircle(Circle_RADIUS_DEF, Circle_RADIUS_DEF, Circle_RADIUS_DEF, Path.Direction.CCW);
    canvas.clipPath(path);

    super.dispatchDraw(canvas);
}

我正在尝试将其裁剪在这里:

path.addCircle(Circle_RADIUS_DEF, Circle_RADIUS_DEF, Circle_RADIUS_DEF, Path.Direction.CCW);
    canvas.clipPath(path);

我没有找到有关剪辑自定义圈子的任何信息。 我已经尝试使用Rect和Arc做到这一点。两者都不起作用。

1 个答案:

答案 0 :(得分:0)

我相信这是您的问题简化了-您有一个圆形的按钮,但是单击按钮的效果好像是一个正方形的表面?如果我错了请纠正我。

如果是这样,则可以使用Paint类放弃并将按钮作为矢量或图像上传到可绘制对象中。然后,从中创建一个ImageView并在其上设置onClickListener。