这段代码来自网上,注释为自己添加:
/**
* 获取带倒影的bitmap,生成的图片高度 = 原图高度 + 间隙高度 + 倒影图片高度(原图的1/2)
*
* @param originalImage
* @return
*/
public static Bitmap createReflectedImage(Bitmap originalImage) {
// 原图和倒影之间的间隙宽度
final int reflectionGap = 8;
int width = originalImage.getWidth();
int height = originalImage.getHeight();
// 使图片上下颠倒的matrix参数
Matrix matrix = new Matrix();
matrix.preScale(1, -1);
// 创建倒影图片,原图的下半部,且上下颠倒
Bitmap reflectionImage = Bitmap.createBitmap(originalImage, 0, height / 2, width,
height / 2, matrix, false);
// 创建带倒影图片的“易变的”bitmap(可以理解为图片的框架),总是推荐使用参数Config.ARGB_8888(每个像素32位)
Bitmap bitmapWithReflection = Bitmap.createBitmap(width, (height + height / 2),
Config.ARGB_8888);
// 使用易变的bitmap创建画布
Canvas canvas = new Canvas(bitmapWithReflection);
// 将原始图片绘制到画布上
canvas.drawBitmap(originalImage, 0, 0, null);
Paint defaultPaint = new Paint();
defaultPaint.setColor(Color.TRANSPARENT);
// 画原图和倒影之间的间隙
canvas.drawRect(0, height, width, height + reflectionGap, defaultPaint);
// 画图片的倒影
canvas.drawBitmap(reflectionImage, 0, height + reflectionGap, null);
Paint paint = new Paint();
// 渐变效果
LinearGradient shader = new LinearGradient(0, originalImage.getHeight(), 0,
bitmapWithReflection.getHeight() + reflectionGap, 0x70ffffff, 0x00ffffff,
TileMode.CLAMP);
paint.setShader(shader);
// Mode.DST_IN为先后绘制的图层的交集,后绘制的图层在上,这里两个图层完全重合,实际上就是渐变遮罩效果
paint.setXfermode(new PorterDuffXfermode(Mode.DST_IN));
// 将渐变遮罩绘制到画布上,覆盖范围:间隙和倒影
canvas.drawRect(0, height, width, bitmapWithReflection.getHeight()
+ reflectionGap, paint);
return bitmapWithReflection;
}