Draw a transparent circle onto a filled android canvas

后端 未结 1 1565
余生分开走
余生分开走 2020-12-16 06:19

\"enter

I am trying to do something very simple (see above). I want all of the pixels

相关标签:
1条回答
  • 2020-12-16 06:58

    Try this:

    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);
        }
    }
    
    0 讨论(0)
提交回复
热议问题