如何在Android画布中擦除(使透明)一个自定义区域?

时间:2012-02-14 14:16:43

标签: android android-canvas android-imageview

我正在重写Android的ImageView,以使我的图像角落透明。我可以在我的onDraw(Canvas画布)中完成剪切画布:

@Override
protected void onDraw(Canvas canvas) {
    Path clipPath = new Path();
    int w = this.getWidth();
    int h = this.getHeight();
    clipPath.addRoundRect(new RectF(0,0,w,h), 10.0f, 10.0f, Path.Direction.CW);
    canvas.clipPath(clipPath);
    super.onDraw(canvas);
}

不幸的是,不可能对这个圆形矩形进行抗锯齿处理,结果就像这样丑陋的角落:

enter image description here

我知道我可以使用PaintPorterDuff.Mode.CLEAR使用抗锯齿来清除部分画布,我不知道的是将圆角指定为要删除的区域。我正在寻找这样的东西:

@Override
protected void onDraw(Canvas canvas) {
    //superclass will draw the bitmap accordingly 
    super.onDraw(canvas);

    final Paint paint = new Paint();
    paint.setAntiAlias(true);
    paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.CLEAR));

    //this will erase a round rectangle, I need the exact inverse
    canvas.drawRoundRect(rect, rx, ry, paint);
}

有没有办法“擦除”不是圆角矩形,但它是相反的,即圆角?如果我只想删除其中一个角落怎么办?

1 个答案:

答案 0 :(得分:4)

使用涂色对象的透明色BitmapShader绘制 如果您只想删除其中一个角,请尝试将其绘制为路径而不是RoundRect。

protected void onDraw(Canvas canvas) {
    BitmapShader bitmapShader = new BitmapShader(<original drawable>, TileMode.CLAMP, TileMode.CLAMP);

    Paint paint = new Paint();
    paint.setAntiAlias(true);
    paint.setColor(0xFF000000);
    paint.setShader(bitmapShader);

    canvas.drawRoundRect(rect, rx, ry, paint);

}