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
)正确显示,但是没有剪切。我还通过调用构造函数尝试了Op
除REPLACE
强制软件光栅化(如我在某些Android版本clipPath
上不支持某些Op
s)外的其他值setLayerType(LAYER_TYPE_SOFTWARE, null);
,但无济于事。如何达到理想的效果?
注意:我的最低SDK版本是15,所以我不需要支持4.0以下的版本。
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)
尝试将路径剪裁为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)
归档时间: |
|
查看次数: |
4242 次 |
最近记录: |