Image Reflection - Tutorial (source code download)


Updated: 16 April 2013

Tested in:
HTC desire S (android 2.3.5), Samsung Galaxy Ace (android 2.3.4)

Base on:
Eclipse Indigo build in 20120216-1857, Java 1.6, Android 4.1.2

Download Source code:
DemoImageReflection20130416.rar

Description:
Image with reflection, for music player or image slideshow...

Screen shot:


Tutorial:
Using this code, the input parameter is a bitmap of an image.
public Bitmap createReflectedImages(Bitmap originalImage) {

  int reflectionGap = 4;

  int width = originalImage.getWidth();

  int height = originalImage.getHeight();

  Matrix matrix = new Matrix();

  matrix.preScale(1, -1);

  Bitmap reflectionImage = Bitmap.createBitmap(originalImage, 0, height / 2, width, height / 2, matrix, false);

  Bitmap bitmapWithReflection = Bitmap.createBitmap(width, (height + height / 2), Config.ARGB_8888);

  Canvas canvas = new Canvas(bitmapWithReflection);

  canvas.drawBitmap(originalImage, 0, 0, null);

  Paint deafaultPaint = new Paint();

  canvas.drawRect(0, height, width, height + reflectionGap, deafaultPaint);

  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);

  paint.setXfermode(new PorterDuffXfermode(Mode.DST_IN));

  canvas.drawRect(0, height, width, bitmapWithReflection.getHeight() + reflectionGap, paint);

  return bitmapWithReflection;
 }
If you want to change the size of reflection, for example, 1/3 of original image, modify this code like:
Bitmap reflectionImage = Bitmap.createBitmap(originalImage, 0, height * 2 / 3, width, height / 3, matrix, false);
Bitmap bitmapWithReflection = Bitmap.createBitmap(width, (height + height / 3), Config.ARGB_8888);

References:
n/a

Leave a Reply

Powered by Blogger.