Android BitmapMesh使图片扭曲

本文介绍了如何使用Android的drawBitmapMesh方法对Bitmap进行扭曲操作。通过指定meshWidth和meshHeight来划分图像网格,verts数组定义了每个顶点的新位置,从而实现图像的变形效果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >



/**

 *
 * 转载请标明出处:
http://blog.youkuaiyun.com/u013598111/article/details/50441772

 *   @author:【JunTao_sun】
 *
 *
*/



drawBitmapMesh(Bitmap bitmap, int meshWidth, int meshHeight, float[] verts, int vertOffset, int[] colors,int colorffset,Paint paint) 
这个方法可以对bitmap进行扭曲
参数说明如下:
bitmap     需要扭曲的源位图
meshWidth   控制在横向上把该源位图划成成多少格
meshHeight   控制在纵向上把该源位图划成成多少格 
verts      长度为(meshWidth + 1) * (meshHeight + 1) * 2的数组,它记录了扭曲后的位图各顶点位置
vertOffset         控制verts数组中从第几个数组元素开始才对bitmap进行扭曲

public class myView extends ImageView {
	int width = 200 + 1;
	int height = 200 + 1;
	int COUNT = width * height;
	float[] verts = new float[COUNT * 2];
	float[] origs = new float[COUNT * 2];

	public myView(Context context, AttributeSet attrs) {
		this(context, attrs, 0);
		// TODO Auto-generated constructor stub
	}

	public myView(Context context) {
		this(context, null);
		// TODO Auto-generated constructor stub
	}

	private Context mContex;
	private Bitmap mBitmap;

	public myView(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
		mContex = context;

	}

	private void initBitmap(int w, int h) {
		mBitmap = BitmapFactory.decodeResource(mContex.getResources(),
				R.drawable.ic_2);

		float rate = Math.max(mBitmap.getWidth() * 1.0f / w,
				mBitmap.getHeight() * 1.0f / h);

		mBitmap = Bitmap.createScaledBitmap(mBitmap,
				(int) (mBitmap.getWidth() / rate),
				(int) (mBitmap.getHeight() / rate), true);
		int index = 0;
		for (int i = 0; i < height; i++) {
			float y = mBitmap.getHeight() * i / height;

			for (int j = 0; j < width; j++) {
				float x = mBitmap.getWidth() * j / width;
				verts[index * 2 + 0] = origs[index * 2 + 0] = x;
				verts[index * 2 + 1] = origs[index * 2 + 1] = y;
				index += 1;

			}
		}
	
	}

	@Override
	protected void onSizeChanged(int w, int h, int oldw, int oldh) {
		// TODO Auto-generated method stub
		super.onSizeChanged(w, h, oldw, oldh);
		initBitmap(w, h);
	}

	float k = 0.0f;

	@Override
	protected void onDraw(Canvas canvas) {
		for (int i = 0; i < height; i++) {

			for (int j = 0; j < width; j++) {

				verts[(i * width + j) * 2 + 0] += 0;
				// float offsetY=(float)
				// Math.sin((float)j/height*Math.PI/180+k);
				float offsetY = (float) Math.sin(Math.PI * 2 * j / height + k);

				verts[(i * width + j) * 2 + 1] = (float) (origs[(i * width + j) * 2 + 1])
						+ offsetY * 15;

			}
		}
		k += 0.1;
		
		canvas.drawBitmapMesh(mBitmap, 200, 200, verts, 0, null, 0, null);
		invalidate();
		// canvas.drawBitmap(mBitmap, 0, 0, null);
	}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值