我目前正在寻找一种方法来使用黑白位图来掩盖另一个位图或 Android 上的 Drawable 的 alpha channel 。我很好奇最好的方法是什么。对于如何做到这一点,我当然有一些想法,但它们并不是最佳的。
我需要能够经常对图像应用新蒙版(黑白位图每隔几秒就会改变一次)。
我们将不胜感激任何有关如何实现这一目标的反馈。
最佳答案
我的解决方案接近@over_optimistic 的解决方案,少了一个 saveLayer() 调用。我使用 Drawable 蒙版而不是路径,在我的情况下它是一张光盘。
我将这些变量声明为字段(最好在 onDraw 方法之外分配内存):
private Paint maskingPaint = new Paint();
private Drawable mask = <insert your drawable here>
然后,在 onDraw() 之外的某个地方设置对象:
// Xfermode won't work if hardware accelerated
setLayerType(View.LAYER_TYPE_SOFTWARE, null);
// Using destination shape as a mask
// For a good explanation of PorterDuff transfer modes : http://ssp.impulsetrain.com/porterduff.html
maskingPaint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
maskingPaint.setAntiAlias(true);
// Position the mask
mask.setBounds(<insert your mask bounds here>);
最后,onDraw() 方法应用掩码:
@Override
protected synchronized void onDraw(Canvas canvas)
{
// Draw the mask first, making it the PorterDuff destination
mask.draw(canvas);
// Save the layer with the masking paint, that will be applied on restore()
// Using CLIP_TO_LAYER_SAVE_FLAG to avoid any overflow of the masked image outside the mask bounds.
Rect bounds = mask.getBounds();
canvas.saveLayer(bounds.left, bounds.top, bounds.right, bounds.bottom, maskingPaint,
Canvas.CLIP_TO_LAYER_SAVE_FLAG);
// Draw the shape offscreen, making it the PorterDuff source
super.onDraw(canvas);
// Apply the source to the destination, using SRC_IN transfer mode
canvas.restore();
}
为了更好地理解传输模式,我引用了 http://ssp.impulsetrain.com/porterduff.html . 那一页读起来很有趣。之后,使用相同类型的代码,您将能够实现的不仅仅是简单的掩码!
关于android - 在 Android 上屏蔽 Drawable/Bitmap,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2623888/