我有一个自定义视图和的OnDraw()
,我想执行的位图屏蔽。我有一个 squareBitmap
(红色),它充满整个来看,我有一个 circleBitmap
(蓝色)的充当掩模。我使用的模式: PorterDuff.Mode.DST_IN
I have a custom view and in the onDraw()
, I am trying to perform bitmap masking. I have a squareBitmap
(red color) which fills the whole view, and I have a circleBitmap
(blue color) that acts as the mask. I am using the mode: PorterDuff.Mode.DST_IN
.
结果,我希望是一个红色实心圆。我明白,但我也得到一个黑色不透明的背景。我不希望这种不透明的背景下,而应该是透明的。 图1
是我找来的,图2
是我期待的结果的结果。
The result I am expecting is a RED filled circle. I get that, but I also get a BLACK opaque background. I don't want this opaque background, rather it should be transparent. Figure 1
is the result I got, and Figure 2
is the result that I am looking for.
我的code:(我已搬到里面的一切的OnDraw()
对这个问题的目的)
My code: (I have moved everything inside onDraw()
for the purpose of this question)
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, 0, width, height);
squareCanvas.drawRect(squareRect, p);
Paint q = new Paint(Paint.ANTI_ALIAS_FLAG);
canvas.drawBitmap(squareBitmap, 0, 0, q);
q.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_IN));
canvas.drawBitmap(circleBitmap, 0, 0, q);
q.setXfermode(null);
}
我在哪里的问题呢?我怎样才能避免这种黑色不透明的背景?
Where am I going wrong? How can I avoid this black opaque background?
推荐答案
似乎得到了 Xfermode
做的,我需要绘制重定向到一个屏幕外的位图。因此,添加以下固定我的问题。
It seems that to get the Xfermode
done, I need to redirect the drawing to an offscreen bitmap. So adding the following fixed my problem.
canvas.saveLayer(0, 0, canvas.getWidth(), canvas.getHeight(), q);
但话又说回来,的文档 saveLayer
说要避免使用此方法,因为它是昂贵的。因此建议使用这种方法的一个 harware层的代替。
But then again, the documentation of saveLayer
says to avoid using this method since it is expensive. It is suggested to use a harware layer instead of this method.
避免使用这种方法,特别是如果提供的范围是大的, 或者如果CLIP_TO_LAYER_SAVE_FLAG从saveFlags省略 参数。建议在查看使用硬件层 施加xfermode,彩色滤光片,或α,因为它会执行许多 比这更好的方法。
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
法的这一翻译,我能够通过添加修复它下面的:
Hence, intead of saveLayer
method, I was able to fix it by adding the following:
setLayerType(LAYER_TYPE_HARDWARE, q);
相关推荐
最新文章