Friday, November 30, 2012

Reflection image of imageview in android

Here I create reflection of image as a shadow of image in android.


Below is full example of this.
My xml file for imageview..

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

        <ImageView
            android:id="@+id/imageView1"
            android:layout_width="150dp"
            android:layout_height="150dp"
            android:src="@drawable/ic_launcher" />
       

</LinearLayout>

Java file for this....


public class MainActivity extends Activity {

 Bitmap bt;
 ImageView i;
 @Override
 public void onCreate(Bundle icicle) {
  super.onCreate(icicle);
  setContentView(R.layout.activity_main);
  
  i = (ImageView) findViewById(R.id.imageView1);
  
   Bitmap bitmap = ((BitmapDrawable)getResources().getDrawable(R.drawable.ic_launcher)).getBitmap();
   bt = reflection(bitmap);
  i.setImageBitmap(bt);
 }
 
 public static Bitmap reflection(Bitmap mainImage) {
        // gap space between original and reflected
        final int reflectionGap = 2;
        // get image size
        int width = mainImage.getWidth();
        int height = mainImage.getHeight();

        Matrix matrix = new Matrix();
        matrix.preScale(1, -1);

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

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

        Canvas canvas = new Canvas(reflectedBitmap);
        canvas.drawBitmap(mainImage, 0, 0, null);
        Paint defaultPaint = new Paint();
        canvas.drawRect(0, height, width, height + reflectionGap, defaultPaint);
        canvas.drawBitmap(reflectionImage, 0, height + reflectionGap, null);
        Paint paint = new Paint();
        LinearGradient shader = new LinearGradient(0,
                mainImage.getHeight(), 0, reflectedBitmap.getHeight()
                        + reflectionGap, 0x70ffffff, 0x00ffffff, TileMode.CLAMP);
        paint.setShader(shader);
        paint.setXfermode(new PorterDuffXfermode(Mode.DST_IN));
        canvas.drawRect(0, height, width, reflectedBitmap.getHeight()
                + reflectionGap, paint);

        return reflectedBitmap;
    }
}



This is the OUTPUT of above example.


2 comments:

  1. Replies
    1. Reduce Gap between reflected image and original image

      final int reflectionGap = 2;
      Change above line of code according to your requirement.

      Delete