画一个透明圈到一个充满安卓帆布 [英] Draw a transparent circle onto a filled android canvas

查看:154
本文介绍了画一个透明圈到一个充满安卓帆布的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图做一些很简单的(见上文)。我希望所有的画布的像素为纯色,除了填补一个圆圈中心的像素。我看过数以百计的叠加对这个问题的溢出后,并尝试数以百计的事情,包括设置PorterDuff.Mode。这是我目前的MyView的的的OnDraw()延伸查看:

I am trying to do something very simple (see above). I want all of the pixels of a canvas to be a solid color, except for the the pixels that fill a centered circle. I have read hundreds stack overflow post on this subject and have tried hundreds of things including setting the PorterDuff.Mode. Here is my current onDraw() of MyView extends View:

  protected void onDraw(Canvas canvas) {
    int w = canvas.getWidth();
    int h = canvas.getHeight();

    Paint framePaint = new Paint();
    framePaint.setStyle(Paint.Style.FILL);
    framePaint.setColor(Color.BLUE);
    canvas.drawRect(0, 0, w, h, framePaint);

    Paint transparentPaint = new Paint();
    transparentPaint.setColor(Color.TRANSPARENT);
    transparentPaint.setAntiAlias(true);
    canvas.drawCircle(w / 2, h / 2, (w + h) / 4, transparentPaint);
  }

我误解的东西,为什么不能我画了透明涂料现有的像素。当我这样做的像素保持不变。当我使用PorterDuff,像素变为黑色。请大家帮帮忙。

Am I misunderstanding something, why cant I paint over an existing pixel with transparent paint. When I do this the pixel stays the same. When I use PorterDuff, the pixel turns black. Please help.

推荐答案

试试这个:

public class TransparentCircle extends View {

    Bitmap bm;
    Canvas cv;
    Paint eraser;

    public TransparentCircle(Context context) {
        super(context);
        Init();
    }

    public TransparentCircle(Context context, AttributeSet attrs) {
        super(context, attrs);
        Init();
    }

    public TransparentCircle(Context context, AttributeSet attrs,
                             int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        Init();
    }

    private void Init(){

        eraser = new Paint();
        eraser.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.CLEAR));
        eraser.setAntiAlias(true);
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {

        if (w != oldw || h != oldh) {
            bm = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
            cv = new Canvas(bm);
        }
        super.onSizeChanged(w, h, oldw, oldh);
    }

    @Override
    protected void onDraw(Canvas canvas) {

        int w = getWidth();
        int h = getHeight();
        int radius = w > h ? h / 2 : w / 2;

        bm.eraseColor(Color.TRANSPARENT);
        cv.drawColor(Color.BLUE);
        cv.drawCircle(w / 2, h / 2, radius, eraser);
        canvas.drawBitmap(bm, 0, 0, null);
        super.onDraw(canvas);
    }
}

这篇关于画一个透明圈到一个充满安卓帆布的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆