Android开发:轻松实现图片倒影效果

效果如下:

<ignore_js_op>

device_thumb.png (68.26 KB, 下载次数: 41)

下载附件  保存到相册

2011-12-11 09:46 上传

 

主要代码如下:

  1. public static Bitmap createReflectedImage(Bitmap originalImage) {
  2.     final int reflectionGap = 4;
  3.     int width = originalImage.getWidth();
  4.     int height = originalImage.getHeight();
  5.     Matrix matrix = new Matrix();
  6.     matrix.preScale(1, -1);
  7.     Bitmap reflectionImage = Bitmap.createBitmap(originalImage, 0,
  8.             height / 2, width, height / 2, matrix, false);
  9.     Bitmap bitmapWithReflection = Bitmap.createBitmap(width,
  10.             (height + height / 2), Config.ARGB_8888);
  11.     Canvas canvas = new Canvas(bitmapWithReflection);
  12.     canvas.drawBitmap(originalImage, 0, 0, null);
  13.     Paint defaultPaint = new Paint();
  14.     canvas.drawRect(0, height, width, height + reflectionGap, defaultPaint);
  15.     canvas.drawBitmap(reflectionImage, 0, height + reflectionGap, null);
  16.     Paint paint = new Paint();
  17.     LinearGradient shader = new LinearGradient(0,
  18.             originalImage.getHeight(), 0, bitmapWithReflection.getHeight()
  19.                     + reflectionGap, 0×70ffffff, 0×00ffffff,
  20.             TileMode.MIRROR);
  21.     paint.setShader(shader);
  22.     paint.setXfermode(new PorterDuffXfermode(Mode.DST_IN));
  23.     canvas.drawRect(0, height, width, bitmapWithReflection.getHeight()
  24.             + reflectionGap, paint);
  25.     return bitmapWithReflection;
  26. }
复制代码

解释一下:

  1. Matrix matrix = new Matrix();
  2.     matrix.preScale(1, -1);
复制代码

实现图片的反转,见Android利用Matrix简单处理图片

  1. Bitmap reflectionImage = Bitmap.createBitmap(originalImage, 0,
  2.             height / 2, width, height / 2, matrix, false);
复制代码

创建反转后的图片Bitmap对象,图片高是原图的一半。

  1. Bitmap bitmapWithReflection = Bitmap.createBitmap(width,
  2.             (height + height / 2), Config.ARGB_8888);
复制代码

创建标准的Bitmap对象,宽和原图一致,高是原图的1.5倍。

  1. Canvas canvas = new Canvas(bitmapWithReflection);
  2.     canvas.drawBitmap(originalImage, 0, 0, null);
复制代码

创建画布对象,将原图画于画布,起点是原点位置。

  1. Paint defaultPaint = new Paint();
  2.     canvas.drawRect(0, height, width, height + reflectionGap, defaultPaint);
  3.     canvas.drawBitmap(reflectionImage, 0, height + reflectionGap, null);
复制代码

将反转后的图片画到画布中。

  1. LinearGradient shader = new LinearGradient(0,
  2.             originalImage.getHeight(), 0, bitmapWithReflection.getHeight()
  3.                     + reflectionGap, 0×70ffffff, 0×00ffffff,
复制代码

创建线性渐变LinearGradient 对象。

  1. canvas.drawRect(0, height, width, bitmapWithReflection.getHeight()
  2.             + reflectionGap, paint);
复制代码

画布画出反转图片大小区域,然后把渐变效果加到其中,就出现了图片的倒影效果。

原文地址:https://www.cnblogs.com/xiaochao1234/p/3530824.html