Canvas.clipPath(Path)未按预期剪切

时间:2012-12-02 19:19:26

标签: android drawing android-canvas image-clipping

我正在尝试将画布绘制操作剪切为弧形楔形。但是,在将剪切路径设置为画布后,我没有得到预期的结果。

为了说明,这是我正在做的事情:

enter image description here

path.reset();

//Move to point #1
path.moveTo(rect.centerX(), rect.centerY());

//Per the documentation, this will draw a connecting line from the current
//position to the starting position of the arc (at 0 degrees), add the arc
//and my current position now lies at #2.
path.arcTo(rect, 0, -30);

//This should then close the path, finishing back at the center point (#3)
path.close();

这是有效的,当我简单地绘制这条路径(canvas.drawPath(path, paint))时,它会绘制如上所示的楔形。但是,当我将此路径设置为画布的剪切路径并绘制到其中时:

//I've tried it with and without the Region.Op parameter
canvas.clipPath(path, Region.Op.REPLACE);
canvas.drawColor(Color.BLUE);

我得到以下结果(仅留下楔形以显示参考):

enter image description here

所以它似乎会剪切到Path的边界矩形,而不是Path本身。任何想法在这里发生了什么?

编辑就像更新一样,我发现了一种更有效的方法,可以实现硬件加速。首先,将整个图像(您要裁剪)绘制到屏幕外位图中。使用此BitmapShader制作Bitmap,将该着色器设置为Paint,然后使用该Paint对象绘制楔形路径:

drawMyBitmap(bitmap);
Shader shader = new BitmapShader(bitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP);
Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
paint.setShader(shader);

@Override
public void onDraw(Canvas canvas) {
    canvas.drawArc(rect,         //The rectangle bounding the circle
                   startAngle,   //The angle (CW from 3 o'clock) to start
                   sweepAngle,   //The angle (CW from 3 o'clock) of the arc
                   true,         //Boolean of whether to draw a filled arc (wedge)
                   paint         //The paint with the shader attached
    );
}

2 个答案:

答案 0 :(得分:12)

您使用的是HC还是以上或其他使用硬件加速?

如果是这样,则不支持clipPath并且有问题。

developer.android.com/guide/topics/graphics/hardware-accel.html

答案 1 :(得分:3)

OP的问题是关于使用剪辑区域的问题,@Simon回答了这个问题。但请记住,有一种更简单的绘制填充弧的方法:

创建Paint

mPaint = new Paint();
mPaint.setColor(Color.BLUE);
mPaint.setStyle(Style.FILL);
mPaint.setAntiAlias(true);

绘图时,只需绘制路径:

canvas.drawPath(path, mPaint);