Android给图片添加倒影效果
给图片添加倒影效果怎么实现呢?我们先看下效果图:
注释很详细,就不多说了。具体实现代码如下:
package com.example.specialeffect_reflectedimages;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.LinearGradient;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.PorterDuffXfermode;
import android.graphics.Bitmap.Config;
import android.graphics.PorterDuff.Mode;
import android.graphics.Shader.TileMode;
import android.os.Bundle;
import android.widget.ImageView;
/*
* 为图片添加倒影
*/
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Bitmap bitmap = createReflectedBitmap(R.drawable.dog);
ImageView imageView = (ImageView) findViewById(R.id.ivTest);
imageView.setImageBitmap(bitmap);
}
/**
* @param imgId 图片资源id
* @return Bitmap 带倒影的Bitmap
*/
private Bitmap createReflectedBitmap(int imgId){
Bitmap originalImage = BitmapFactory.decodeResource(getResources(), imgId);
// 反射图片和原始图片中间的间距
final int reflectionGap = 4;
int width = originalImage.getWidth();
int height = originalImage.getHeight();
//通过矩阵对图像进行变换
Matrix matrix = new Matrix();
// 第一个参数为1,表示x方向上以原比例为准保持不变,正数表示方向不变。
// 第二个参数为-1,表示y方向上以原比例为准保持不变,负数表示方向取反。
matrix.preScale(1, -1); // 实现图片的反转
// 创建反转后的图片Bitmap对象,图片高是原图的一半
Bitmap reflectionImage = Bitmap.createBitmap(originalImage, 0,
height / 2, width, height / 2, matrix, false);
// 创建标准的Bitmap对象,宽和原图一致,高是原图的1.5倍
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 对象。
LinearGradient shader = new LinearGradient(0, originalImage
.getHeight(), 0, bitmapWithReflection.getHeight()
+ reflectionGap, 0x70ffffff, 0x00ffffff, TileMode.MIRROR);
paint.setShader(shader);
// 倒影遮罩效果
paint.setXfermode(new PorterDuffXfermode(Mode.DST_IN));
canvas.drawRect(0, height, width, bitmapWithReflection.getHeight()
+ reflectionGap, paint);
return bitmapWithReflection;
}
}
布局文件:
<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="${relativePackage}.${activityClass}" >
<ImageView
android:id="@+id/ivTest"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:contentDescription="@null"
android:layout_centerHorizontal="true" />
</RelativeLayout>