我有一个自定义视图,在onDraw()中,我正在尝试执行位图屏蔽.我有一个squareBitmap(红色)填充整个视图,我有一个circleBitmap(蓝色)作为掩码.我使用的模式:PorterDuff.Mode.DST_IN.
我期待的结果是一个红色的圆圈.我明白了,但我也得到了一个黑色的不透明背景.我不想要这种不透明的背景,而应该是透明的.图1是我得到的结果,图2是我要找的结果.
我的代码:(为了这个问题的目的,我已经将所有内容都移到了onDraw()中)
protected void onDraw(Canvas canvas) { final int width = canvas.getWidth(); final int height = canvas.getHeight(); Bitmap circleBitmap = Bitmap.createBitmap(width,height,Bitmap.Config.ARGB_8888); Canvas circleCanvas = new Canvas(circleBitmap); Paint p = new Paint(Paint.ANTI_ALIAS_FLAG); p.setStyle(Paint.Style.FILL_AND_STROKE); p.setColor(Color.BLUE); circleCanvas.drawCircle(width / 2,height / 2,width / 2,p); p.setColor(Color.RED); Bitmap squareBitmap = Bitmap.createBitmap(canvas.getWidth(),canvas.getHeight(),Bitmap.Config.ARGB_8888); Canvas squareCanvas = new Canvas(squareBitmap); final Rect squareRect = new Rect(0,width,height); squareCanvas.drawRect(squareRect,p); Paint q = new Paint(Paint.ANTI_ALIAS_FLAG); canvas.drawBitmap(squareBitmap,q); q.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_IN)); canvas.drawBitmap(circleBitmap,q); q.setXfermode(null); }
我哪里错了?如何避免这种黑色不透明背景?
解决方法
似乎要完成Xfermode,我需要将绘图重定向到屏幕外位图.所以添加以下内容解决了我的问题.
canvas.saveLayer(0,canvas.getWidth(),q);
但话说再说一次,saveLayer的documentation表示要避免使用这种方法,因为它很昂贵.建议使用harware layer而不是此方法.
Avoid using this method,especially if the bounds provided are large,
or if the CLIP_TO_LAYER_SAVE_FLAG is omitted from the saveFlags
parameter. It is recommended to use a hardware layer on a View to
apply an xfermode,color filter,or alpha,as it will perform much
better than this method.
因此,在saveLayer方法的内容中,我能够通过添加以下内容来修复它:
setLayerType(LAYER_TYPE_HARDWARE,q);