如何在Android中仅屏蔽位图的某些部分

时间:2013-12-23 20:33:39

标签: android android-layout

我希望能够使用以下图像来屏蔽其他位图。所以基本上,我正在尝试获取蒙版图像并用另一个位图替换它的黑色内容。像这样举例如:

This is the mask This is the final result

我可以使用这个遮罩并创建原始位图的圆形版本,但这并不会保留它周围的橙色边框。有关如何实现这种效果的任何想法?感谢。

我正在使用的代码(仅创建圆形图像)如下:

private static Bitmap applyMask(ImageView imageView, Bitmap mainImage) {
    Canvas canvas = new Canvas();

    Bitmap result result = Bitmap.createBitmap(50, 50, Bitmap.Config.ARGB_8888);            

    canvas.setBitmap(result);
    Paint paint = new Paint();

    // resize image fills the whole canvas
    canvas.drawBitmap(mainImage, null, new Rect(0,  0, 50, 50), paint);

    paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_IN));
    canvas.drawBitmap(sMaskImage, 0, 0, paint);
    paint.setXfermode(null);

    return result;
}

1 个答案:

答案 0 :(得分:1)

我使用下面的代码剪切来设置屏蔽图像,此示例“bm”是我的位图,“mMaskSource”是我的drawable文件夹中屏蔽对象位置的资源ID。

Bitmap mask = BitmapFactory.decodeResource(getResources(), mMaskSource);
Bitmap result = Bitmap.createBitmap(mask.getWidth(), mask.getHeight(),
            Config.ARGB_8888);
Canvas mCanvas = new Canvas(result);
Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_IN));
bm = Bitmap.createScaledBitmap(bm, mask.getWidth(), mask.getHeight(),
            true);
mCanvas.drawBitmap(bm, 0, 0, null);
mCanvas.drawBitmap(mask, 0, 0, paint);
paint.setXfermode(null);

最后,您可以根据需要使用“result”位图对象。