Android进阶学习-实现图片倒影的效果

效果图:

参考:着色器/渲染器

首先说一下原理,这是一张图片A,然后通过拷贝成图片B,再把B翻转,翻转后再设置B+一个渐变色的混合,实现渐变.

 

1.布局文件:

<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="com.example.customview.ReflectActivity" >

    <com.example.customview.ReflectView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true" />

</RelativeLayout>

2.编码:

package com.example.customview;

import android.content.Context;
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.Shader.TileMode;
import android.util.AttributeSet;
import android.view.View;

public class ReflectView extends View {
	
	private Bitmap	mBitmap;
	private Bitmap	mRefBitmap;
					
	public ReflectView(Context context, AttributeSet attrs, int defStyleAttr) {
		super(context, attrs, defStyleAttr);
	}
	
	public ReflectView(Context context) {
		super(context, null);
	}
	
	public ReflectView(Context context, AttributeSet attrs) {
		super(context, attrs, 0);
		mBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.jpg);
		/**
		 * 这是上面的那张图片A
		 */
		
		Matrix matrix = new Matrix();
		matrix.setScale(1f, -1f);
		/**
		 * 使图片上下翻转的矩阵运算
		 */
		
		mRefBitmap = Bitmap.createBitmap(mBitmap, 0, 0, mBitmap.getWidth(), mBitmap.getHeight(), matrix, true);
		/**
		 * 拷贝图片A并翻转
		 */
		
		Paint paint = new Paint();
		LinearGradient linearGradient = new LinearGradient(0, 0, 0, mBitmap.getHeight() / 4, 0X00000000, 0XFF000000,
				TileMode.CLAMP);
		paint.setShader(linearGradient);
		/**
		 * 这是使图片B渐变的渲染器 让颜色从透明-->黑色
		 */
		
		Canvas canvas = new Canvas(mRefBitmap);
		canvas.drawRect(0, 0, mBitmap.getWidth(), mBitmap.getHeight() / 4, paint);
		/**
		 * 然后开始在mRefBitmap上画出渐变效果
		 */
	}
	
	@Override
	protected void onDraw(Canvas canvas) {
		super.onDraw(canvas);
		canvas.clipRect(0, 0, mBitmap.getWidth(), mBitmap.getHeight() + mBitmap.getHeight() / 4);
		/**
		 * 只在有效区域(宽度为图片宽度,高度为图片高度+倒影的高度)内作画,其他超出有效区域的裁剪掉
		 */
		
		/**
		 * 最后把两张图片拼接
		 */
		canvas.drawBitmap(mBitmap, 0, 0, null);
		canvas.drawBitmap(mRefBitmap, 0, mBitmap.getHeight(), null);
	}
}

 

转载于:https://my.oschina.net/august1996/blog/679339

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值