做一个项目的时候需要给图片加上倒影效果,下面是其实现方法。
/*
* 给图片加上倒影
* @param reflectionGap 倒影和原图之间的距离
* @param reflectionScaleHeight 倒影占原图高度的比例
*/
public static final Bitmap createReflectedImages(Bitmap bitmap,int reflectionGap,double reflectionScaleHeight)
{
int width=bitmap.getWidth();
int height=bitmap.getHeight();
//倒影的高度
int reflectionHeight=(int) (height*reflectionScaleHeight);
//创建矩阵对象
Matrix matrix = new Matrix();
//指定一个角度以0,0为坐标进行旋转
// matrix.setRotate(30);
//指定矩阵(x轴不变,y轴相反)
matrix.preScale(1, -1);
//将矩阵应用到该原图之中,返回一个宽度不变,高度为原图1/2的倒影位图
Bitmap reflectionImage = Bitmap.createBitmap(bitmap, 0,
reflectionHeight, width, reflectionHeight, matrix, false);
//最终要返回的图的高度
int returnBitHeight=height + reflectionHeight+reflectionGap;
//创建一个宽度不变,高度为原图+倒影图高度的位图
Bitmap bitmapWithReflection = Bitmap.createBitmap(width,returnBitHeight, Config.ARGB_8888);
//将上面创建的位图初始化到画布
Canvas canvas = new Canvas(bitmapWithReflection);
canvas.drawBitmap(bitmap, 0, 0, null);
//canvas.drawRect(0, height, width, height + reflectionGap,deafaultPaint);
canvas.drawBitmap(reflectionImage, 0, height + reflectionGap, null);
/**
* 参数一:为渐变起初点坐标x位置,
* 参数二:为y轴位置,
* 参数三和四:分辨对应渐变终点,
* 最后参数为平铺方式,
* 这里设置为镜像Gradient是基于Shader类,所以我们通过Paint的setShader方法来设置这个渐变
*/
LinearGradient shader = new LinearGradient(0,height, 0,
returnBitHeight,0x20ffffff, 0x00ffffff, TileMode.MIRROR);
//设置阴影
Paint paint = new Paint();
paint.setAntiAlias(true);
paint.setShader(shader);
paint.setXfermode(new PorterDuffXfermode(android.graphics.PorterDuff.Mode.DST_IN));
//用已经定义好的画笔构建一个矩形阴影渐变效果
canvas.drawRect(0, height, width, returnBitHeight, paint);
bitmap.recycle();
reflectionImage.recycle();
return bitmapWithReflection;
}