如何在Android中在矩形内剪切圆形路径

Can*_*ğlu 6 android clipping custom-draw ondraw android-4.0-ice-cream-sandwich

我已经阅读了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);


}
Run Code Online (Sandbox Code Playgroud)

我的背景(setARGB)正确显示,但是没有剪切。我还通过调用构造函数尝试了OpREPLACE强制软件光栅化(如我在某些Android版本clipPath上不支持某些Ops)外的其他值setLayerType(LAYER_TYPE_SOFTWARE, null);,但无济于事。如何达到理想的效果?

注意:我的最低SDK版本是15,所以我不需要支持4.0以下的版本。

Roj*_*Roj 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);
}
Run Code Online (Sandbox Code Playgroud)

结果


Gil*_*yof 4

尝试将路径剪裁为dispatchDraw()

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

    super.dispatchDraw(canvas);
}
Run Code Online (Sandbox Code Playgroud)

从您的方法中删除路径剪切代码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);
}
Run Code Online (Sandbox Code Playgroud)

  • 复制/粘贴它。还是没有变化。我非常怀疑除了“onDraw”之外还应该有一个被重写的方法,因为我见过的所有示例都只涉及该方法。 (2认同)