android drawBitmapMesh


package com.example.and6;

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.util.AttributeSet;
import android.widget.ImageView;

public class MeshView  extends ImageView{
	Bitmap bitmap;

	//分割成50*50个格
	int WIDTH=50;
	int HEIGHT=50;
	//依次存放每一个点的 x y坐标
	float[]origs=new float[ ( (WIDTH+1)*(HEIGHT+1)  )*2];
	float[]verts=new float[origs.length];
	
	float k;

	boolean isStart=false;
	public MeshView(Context context) {
		super(context);
		init();
		
	}
	public MeshView(Context context, AttributeSet attrs) {
		super(context, attrs);
		init();
		
	}
	public MeshView(Context context, AttributeSet attrs, int defStyleAttr) {
		super(context, attrs, defStyleAttr);
		init();
		
	}
	@SuppressLint("NewApi")
	public MeshView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
		super(context, attrs, defStyleAttr, defStyleRes);
		init();
		
	}
	@Override
	protected void onDraw(Canvas canvas) {
		super.onDraw(canvas);
		flagWave();
		k+=0.1f;
		
		canvas.drawBitmapMesh(bitmap, WIDTH, HEIGHT, verts, 0, null, 0, null);
		if (isStart) {
			invalidate();

		}
				
	}
	
	public void startAnim() {
		isStart=true;
		requestLayout();
	}
	
	public void stopAnim() {
		isStart=false;
	}
	private void init() {
		bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.pic);

		float bitmapHeight=bitmap.getHeight();
		float bitmapWidth=bitmap.getHeight();
		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;
				
				origs[index*2+0]=verts[index*2+0]=fx;
				origs[index*2+1]=verts[index*2+1]=fy;
				index++;
			}
		}
	}
	private void flagWave() {
		for (int j = 0;j <= HEIGHT; j++) {
			for (int i = 0; i <= WIDTH; i++) {
				verts[ (j*(WIDTH+1)+i )*2+0 ]+=0;
				float offsetY=(float) Math.sin( i*1.0f/WIDTH*2*Math.PI + Math.PI*k);//k 实现周期变化
				
				verts[ (j*(WIDTH+1)+i )*2+1 ]=origs[ ( j*WIDTH+i )*2+1 ]+offsetY*100; //100 振幅
				
			}
		}
	}

}


你可能感兴趣的:(android)