package org.yang.android.util.graphics; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.LinearGradient; import android.graphics.Matrix; import android.graphics.Paint; import android.graphics.PorterDuffXfermode; import android.graphics.Bitmap.Config; import android.graphics.PorterDuff.Mode; import android.graphics.Shader.TileMode; public class ReflectionImage { public static int reflectionGap; public static int reflectImageHeight; public static Bitmap doReflection(Bitmap originalBitmap) { if (originalBitmap == null) { return null; } // 获取原图片的宽度和高度 int width = originalBitmap.getWidth(); int height = originalBitmap.getHeight(); if (ReflectionImage.reflectImageHeight == 0) { ReflectionImage.reflectImageHeight = height / 3; } // 图片缩放,x轴变为原来的1倍,y轴为-1倍,实现图片的反转 Matrix matrix = new Matrix(); matrix.preScale(1, -1); // 创建反转后的图片Bitmap对象,高度为 ReflectionImage.reflectImageHeight Bitmap reflectionBitmap = Bitmap.createBitmap(originalBitmap, 0, ReflectionImage.reflectImageHeight, width, ReflectionImage.reflectImageHeight, matrix, false); // 创建标准的Bitmap对象,宽和原图一致,高度为( 原图与倒影图的间距+倒影图的高度+原图的高度) Bitmap withReflectionBitmap = Bitmap .createBitmap( width, (height + ReflectionImage.reflectImageHeight + ReflectionImage.reflectionGap), Config.ARGB_8888); // 创建一个画面,以 withReflectionBitmap 为模板 Canvas canvas = new Canvas(withReflectionBitmap); // 从上到下,先画原图 canvas.drawBitmap(originalBitmap, 0, 0, null); // 因为 drawRect需要一个Paint画笔对象为参数,这里创建的是一个默认的Paint对象 Paint defaultPaint = new Paint(); // 再画间距 canvas.drawRect(0, height, width, height + ReflectionImage.reflectionGap, defaultPaint); // 最后画倒影图 canvas.drawBitmap(reflectionBitmap, 0, height + reflectionGap, null); Paint paint = new Paint(); // 这里用 LinearGradient 以实现倒影图的渐变效果 LinearGradient shader = new LinearGradient(0, originalBitmap.getHeight(), 0, withReflectionBitmap.getHeight(), 0x70ffffff, 0x00ffffff, TileMode.MIRROR); paint.setShader(shader); paint.setXfermode(new PorterDuffXfermode(Mode.DST_IN)); // 覆盖效果 canvas.drawRect(0, height, width, withReflectionBitmap.getHeight(), paint); return withReflectionBitmap; } }