main.activity如下:
package c.c; import android.os.Bundle; import android.widget.ImageView; import android.app.Activity; import android.graphics.Bitmap; import android.graphics.Bitmap.Config; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.LinearGradient; import android.graphics.Matrix; import android.graphics.Paint; import android.graphics.PorterDuff.Mode; import android.graphics.PorterDuffXfermode; import android.graphics.Shader.TileMode; /** * Demo:生成Bitmap的倒影 */ public class MainActivity extends Activity { private ImageView mImageView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); mImageView=(ImageView) findViewById(R.id.imageView); Bitmap rawBitmap=BitmapFactory.decodeResource(getResources(), R.drawable.a); Bitmap newBitmap=getBitmapReflection(rawBitmap); mImageView.setImageBitmap(newBitmap); } private Bitmap getBitmapReflection(Bitmap rawBitmap) { final int gap = 4; int width = rawBitmap.getWidth(); int height = rawBitmap.getHeight(); Matrix matrix = new Matrix(); //逆置 matrix.preScale(1, -1); //倒影 Bitmap reflectionBitmap = Bitmap.createBitmap(rawBitmap, 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(rawBitmap, 0, 0, null); Paint paint=new Paint(); //画分界线 canvas.drawRect(0, height, width, height + gap, paint); //画倒影 canvas.drawBitmap(reflectionBitmap, 0, height + gap, null); //沿Y轴渐变效果 LinearGradient shader = new LinearGradient(0, rawBitmap.getHeight(), 0, bitmapWithReflection.getHeight() + gap, 0x70ffffff,0x00ffffff, TileMode.CLAMP); paint.setShader(shader); //因为有两层(倒影层和渐变),所以设置过渡模式 paint.setXfermode(new PorterDuffXfermode(Mode.DST_IN)); //画一个具有渐变效果的矩形 canvas.drawRect(0, height, width, bitmapWithReflection.getHeight()+ gap, paint); return bitmapWithReflection; } }
main.xml如下:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity" > <ImageView android:id="@+id/imageView" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerHorizontal="true" android:layout_centerVertical="true" /> </RelativeLayout>
时间: 2024-09-13 03:38:35