11

我已经阅读了 20 多个问题/答案,但我仍然无法得到我想要的。我想在矩形内切一个圆,如下所示:

在此处输入图像描述

这是我的代码:

@Override
protected void onDraw(Canvas canvas) {
    Paint paint = new Paint();
    paint.setStyle(Paint.Style.FILL);
    paint.setARGB(180, 0, 0, 0);
    canvas.drawRect(0, 0, getWidth(), getHeight(), paint);
    Path circularPath = new Path();
    circularPath.addCircle(getWidth() / 2, getHeight() / 2, radius, Path.Direction.CCW);
    canvas.clipPath(circularPath, Region.Op.REPLACE);
    canvas.drawColor(0x00000000);


}

我的背景 ( setARGB) 显示正确,但没有任何内容被剪裁。我还通过调用构造函数尝试了除强制软件光栅化Op之外的其他值REPLACE(正如我在某些 Android 版本上读到的clipPath不支持某些s) ,但无济于事。如何达到预期的效果?OpsetLayerType(LAYER_TYPE_SOFTWARE, null);

注意:我的最低 SDK 版本是 15,所以我不需要支持低于 4.0 的任何东西。

4

2 回答 2

5

clipPath之前使用drawRect

@Override
protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);

    int width = this.getWidth();
    int height = this.getHeight();

    mPaint.setAntiAlias(true);
    mPaint.setColor(Color.WHITE);
    mPaint.setStyle(Paint.Style.FILL);
    canvas.drawPaint(mPaint);

    float rectWidth = Utils.dpToPx(100.0f);

    Path circularPath = new Path();
    circularPath.addCircle(width / 2.0f, rectWidth / 2.0f, rectWidth / 3.0f, Path.Direction.CCW);
    canvas.clipPath(circularPath, Region.Op.DIFFERENCE);

    mPaint.setColor(Color.BLUE);
    canvas.drawRect((width - rectWidth) / 2.0f, 0.0f, ((width - rectWidth) / 2.0f) + rectWidth, rectWidth, mPaint);
}

结果

于 2018-10-15T19:31:40.973 回答
3

尝试将您的路径剪裁为dispatchDraw()

@Override
protected void dispatchDraw(Canvas canvas)
{
    canvas.clipPath(mClipPath, mRegion); // previously created path & region

    super.dispatchDraw(canvas);
}

从您的onDraw方法中删除路径剪辑代码,应该这样做。

编辑:

创建路径时,请确保仅在测量发生后才这样做,例如:

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec)
{
    super.onMeasure(widthMeasureSpec, heightMeasureSpec);

    mClipPath.reset();
    float radius = Math.min((float)getMeasuredWidth() / 2f, (float)getMeasuredHeight() / 2f) + 5;
    mClipPath.addCircle((float)getMeasuredWidth() / 2f, (float)getMeasuredHeight() / 2f, radius, Path.Direction.CCW);
}
于 2015-04-05T14:26:39.423 回答