一、设置图片的透明度从左到右渐变
/**
* 设置图片的透明度从左到右渐变,使右边缘平滑过渡(注意只跟着x坐标变)
*
* @param num 范围为0-100,0为全透明,100为不透明
*/
public static Bitmap getTransAlphaBitmap(Bitmap sourceImg, float num) {
if (sourceImg == null) {
return null;
}
int width = sourceImg.getWidth();
int height = sourceImg.getHeight();
int[] bitArr = new int[width * height];
sourceImg.getPixels(bitArr, 0, width, 0, 0, width, height);
float number = num;
int start = width / DEFAULT_PERCENT;
float range = width - start;
try {
float step = (number * 1.0f) / range;
for (int j = 0; j < height; j++) {
number = num;
for (int i = start + j * width; i < width * (j + 1); i++) {
number = number - step;
float alpha = number * ALPAH_FULL / NUMBER_FULL;
bitArr[i] = ((int) alpha << DEFAULT_BIT) | (bitArr[i] & DEFAULT_ALPHA);
}
}
return Bitmap.createBitmap(bitArr, width, height, Bitmap.Config.ARGB_8888);
} catch (Throwable e) {
return sourceImg;
}
}
二、设置图片的透明度从上到下渐变
/**
* 设置图片的透明度从上到下渐变,使下边缘平滑过渡(注意只跟着Y坐标变)
*
* @param sourceImg
* @return
*/
public static Bitmap getTransAlphaBitmap(Bitmap sourceImg) {
int[] argb = new int[sourceImg.getWidth() * sourceImg.getHeight()];
sourceImg.getPixels(argb, 0, sourceImg.getWidth(), 0, 0, sourceImg
.getWidth(), sourceImg.getHeight());// 获得图片的ARGB值
//number的范围为0-100,0为全透明,100为不透明
float number = 100;
//透明度数值
float alpha = number * 255 / 100;
//图片渐变的范围(只设置图片一半范围由上到下渐变,上面不渐变,即接近边缘的那一半)
float range = sourceImg.getHeight() / 2.0f;
//透明度渐变梯度,每次随着Y坐标改变的量,因为最终在边缘处要变为0
float pos = (number * 1.0f) / range;
//循环开始的下标,设置从什么时候开始改变
int start = sourceImg.getWidth() * (sourceImg.getHeight() - (int) range);
for (int i = start; i < argb.length; i++) {
//同一行alpha数值不改变,因为是随着Y坐标从上到下改变的
if (i % sourceImg.getWidth() == 0) {
number = number - pos;
alpha = number * 255 / 100;
}
argb[i] = ((int) alpha << 24) | (argb[i] & 0x00FFFFFF);
}
sourceImg = Bitmap.createBitmap(argb, sourceImg.getWidth(), sourceImg
.getHeight(), Bitmap.Config.ARGB_8888);
return sourceImg;
}