码迷,mamicode.com
首页 > 移动开发 > 详细

Android-Canvas.drawBitmapMesh给照片底部添加波浪效果

时间:2015-07-29 14:02:21      阅读:455      评论:0      收藏:0      [点我收藏+]

标签:

实现的效果是酱紫的:

技术分享

使用方式跟普通的ImageView是一样的,代码:

/**
 * 参考:http://blog.csdn.net/lee576/article/details/7900228
 * */
public class WaveBottomImageView extends ImageView{

	private Bitmap mBitmap;
	private boolean inited;

	// 定义两个常量,这两个常量指定该图片横向,纵向上都被划分为100格
	private final int WIDTH = 100;
	private final int HEIGHT = 100;

	// 记录该图片上包含10201个顶点
	private final int COUNT = (WIDTH + 1) * (HEIGHT + 1);

	// 定义一个数组,记录Bitmap上的101*101个点的坐标
	private final float[] orig = new float[COUNT * 2];

	// 定义一个数组,记录Bitmap上的101*101个点经过扭曲后的坐标
	// 对图片扭曲的关键就是修改该数组里元素的值
	private final float[] verts = new float[COUNT * 2];

	private int bitmapWidth;
	private int bitmapHeight;
	private float boxHeigtht;

	public WaveBottomImageView(Context context) {
		this(context, null);
	}

	public WaveBottomImageView(Context context, AttributeSet attrs) {
		super(context, attrs);
		mBitmap = ((BitmapDrawable)this.getDrawable()).getBitmap(); 
	}

	@Override
	protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
		super.onMeasure(widthMeasureSpec, heightMeasureSpec);
		// 获取图片宽度和高度
		bitmapWidth = getMeasuredWidth(); 
		bitmapHeight = getMeasuredHeight();
		boxHeigtht = bitmapHeight / HEIGHT;
		
		setMeasuredDimension(bitmapWidth, (int)(bitmapHeight + boxHeigtht));
		
		if(!inited){
			init();	
			inited = true;
		}
	}

	protected void onDraw(Canvas canvas) {
		canvas.drawBitmapMesh(mBitmap, WIDTH, HEIGHT, verts, 0, null, 0, null);
	}

	private void init(){
		//初始化
		int index = 0;
		for (int y = 0; y <= HEIGHT; y++) {
			float fy = bitmapHeight * y / HEIGHT;
			for (int x = 0; x <= WIDTH; x++) {
				float fx = bitmapWidth * x / WIDTH;
				// 初始化orig,verts数组
				// 初始化,orig,verts两个数组均匀地保存了101*101个点的x,y坐标 
				orig[index * 2 + 0] = verts[index * 2 + 0] = fx;
				orig[index * 2 + 1] = verts[index * 2 + 1] = fy;
				if(y == HEIGHT){
					// 修改最后一行的y坐标
					float oldY = orig[index * 2 + 1];
					float newY = (float) (oldY + boxHeigtht * Math.sin(Math.PI / 4 * (x % 5)));
					verts[index * 2 + 1] = newY;
				}
				index += 1;
			}
		}
	}
	
//	private void wave() {
//		int index = (WIDTH + 1) * HEIGHT;
//		for (int x = 0; x <= WIDTH; x++) {
//			float oldY = orig[index * 2 + 1];
//			float newY = (float) (oldY + boxHeigtht * Math.sin(Math.PI / 4 * (x % 5)));
//			verts[index * 2 + 1] = newY;
//			index += 1;
//		}
//	}
}

最开始没有重写onMeasure,导致波浪效果怎么也出不来,妈蛋的!

版权声明:本文为博主原创文章,未经博主允许不得转载。

Android-Canvas.drawBitmapMesh给照片底部添加波浪效果

标签:

原文地址:http://blog.csdn.net/goldenfish1919/article/details/47126691

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!