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

时间:2015-04-05 14:17:26

标签: android android-4.0-ice-cream-sandwich ondraw clipping custom-draw

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

enter image description here

这是我的代码:

@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不支持部分Op s)通过在构造函数上调用setLayerType(LAYER_TYPE_SOFTWARE, null);,但无济于事。我如何达到预期的效果?

注意:我的最低SDK版本是15,因此我不需要支持低于4.0的任何内容。

2 个答案:

答案 0 :(得分:2)

尝试在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);
}

答案 1 :(得分:-1)

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);
}

Result