原图:
目标图:
目标图的效果是取得了原图中间部泡形状的部分。
获取方法:
首先,准备一张目标形状的背景图,这里我的背景图如下:
除黑色部分以外其余部分是透明的。
然后,就是代码了。
原理:先截取原图中响应位置的图片,然后取得背景图中各个像素的透明度,将该透明度赋值给截取后的图片,就ok了。
public static Bitmap getBubbleImage(Bitmap src, Bitmap overlay) {
//原图比背景图大时,截取得原图的中间部分;
//原图比背景图小时,取整个原图;
int width = src.getWidth();
int height = src.getHeight();
int w = overlay.getWidth();
int h = overlay.getHeight();
int offsetX = 0;
int offsetY = 0;
if (width > w) {
offsetX = (width - w) / 2;
}
if (height > h) {
offsetY = (height - h) / 2;
}
Matrix matrix = new Matrix();
int newWidth = Math.min(w, width) - 2;
int newHeight = Math.min(h, height) - 2;
Bitmap bitmap = Bitmap.createBitmap(newWidth, newHeight,
Bitmap.Config.ARGB_8888);
Bitmap srcCopy = Bitmap.createBitmap(src, offsetX, offsetY, newWidth,
newHeight, matrix, true);
//获取背景图个像素的透明度值,赋值给截取后的图
int pixColor = 0;
int layColor = 0;
int newColor = 0;
int pixR = 0;
int pixG = 0;
int pixB = 0;
int layA = 0;
int[] srcPixels = new int[newWidth * newHeight];
int[] overlayPixels = new int[newWidth * newHeight];
int[] targetPixels = new int[newWidth * newHeight];
srcCopy.getPixels(srcPixels, 0, newWidth, 0, 0, newWidth, newHeight);
overlay.getPixels(overlayPixels, 0, newWidth, 0, 0, newWidth, newHeight);
for (int i = 0; i < srcPixels.length; i++) {
pixColor = srcPixels[i];
layColor = overlayPixels[i];
pixR = Color.red(pixColor);
pixG = Color.green(pixColor);
pixB = Color.blue(pixColor);
layA = Color.alpha(layColor);
newColor = Color.argb(layA, pixR, pixG, pixB);
targetPixels[i] = newColor;
}
bitmap.setPixels(targetPixels, 0, newWidth, 0, 0, newWidth, newHeight);
return bitmap;
}