首先,贴出效果图:
1.布局文件main.xml
<?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" > <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/hello" /> <ImageView android:id="@+id/picture_qian" android:layout_width="fill_parent" android:layout_height="fill_parent" android:src="@drawable/horse" /> </LinearLayout>
2.MainActivity界面java代码:
1 package com.easymorse.picture; 2 3 import android.app.Activity; 4 import android.graphics.Bitmap; 5 import android.graphics.Bitmap.Config; 6 import android.graphics.Canvas; 7 import android.graphics.LinearGradient; 8 import android.graphics.Matrix; 9 import android.graphics.Paint; 10 import android.graphics.PorterDuff.Mode; 11 import android.graphics.PorterDuffXfermode; 12 import android.graphics.Shader.TileMode; 13 import android.graphics.drawable.BitmapDrawable; 14 import android.os.Bundle; 15 import android.widget.ImageView; 16 17 public class MainActivity extends Activity { 18 /** Called when the activity is first created. */ 19 @Override 20 public void onCreate(Bundle savedInstanceState) { 21 super.onCreate(savedInstanceState); 22 setContentView(R.layout.main); 23 ImageView imageView2 = (ImageView) findViewById(R.id.picture_qian); 24 25 Bitmap bmp = ((BitmapDrawable) getResources().getDrawable( 26 R.drawable.horse)).getBitmap(); 27 28 imageView2.setImageBitmap(createReflectedImage(bmp)); 29 } 30 31 public static Bitmap createReflectedImage(Bitmap originalImage) { 32 33 final int reflectionGap = 4; 34 35 int width = originalImage.getWidth(); 36 int height = originalImage.getHeight(); 37 38 Matrix matrix = new Matrix(); 39 matrix.preScale(1, -1); 40 41 Bitmap reflectionImage = Bitmap.createBitmap(originalImage, 0, 42 height / 2, width, height / 2, matrix, false); 43 44 Bitmap bitmapWithReflection = Bitmap.createBitmap(width, 45 (height + height / 2), Config.ARGB_8888); 46 47 Canvas canvas = new Canvas(bitmapWithReflection); 48 49 canvas.drawBitmap(originalImage, 0, 0, null); 50 51 Paint defaultPaint = new Paint(); 52 canvas.drawRect(0, height, width, height + reflectionGap, defaultPaint); 53 54 canvas.drawBitmap(reflectionImage, 0, height + reflectionGap, null); 55 56 Paint paint = new Paint(); 57 LinearGradient shader = new LinearGradient(0, 58 originalImage.getHeight(), 0, bitmapWithReflection.getHeight() 59 + reflectionGap, 0x70ffffff, 0x00ffffff, 60 TileMode.MIRROR); 61 62 paint.setShader(shader); 63 64 paint.setXfermode(new PorterDuffXfermode(Mode.DST_IN)); 65 66 canvas.drawRect(0, height, width, bitmapWithReflection.getHeight() 67 + reflectionGap, paint); 68 69 return bitmapWithReflection; 70 } 71 }