package com.moredo.drawbitamp;
import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.view.View;
@SuppressLint(“DrawAllocation”)
public class FlagGril extends View {
private Context mContext;///< 上下文环境
private Bitmap bm;///< 图片
private final int HEIGHT = 100;///< 竖着的网格数
private final int WIDTH = 100;///< 横着的网格数
private float[] orig,verts;///< 原始坐标点,改变后的坐标点
private int A = 30;///< 波动的力度
private float k = 1;
public FlagGril(Context context) {
super(context);
this.mContext = context;
bm = BitmapFactory.decodeResource(mContext.getResources(), R.drawable.gril);
orig = new float[(HEIGHT + 1) * (WIDTH + 1) * 2];
verts = new float[(HEIGHT + 1) * (WIDTH + 1) * 2];
///< 初始化坐标
initOrig();
}
private void initOrig()
{
///< 获取位图的宽高
float width = bm.getWidth();
float height = bm.getHeight();
int index = 0 ;
for(int y = 0 ; y <= HEIGHT ;y++)
{
///< 纵坐标
float fy = height * y / HEIGHT;
for(int x = 0;x <= WIDTH ; x++)
{
///< 横坐标
float fx = width * x / WIDTH ;
orig[index * 2 + 0] = verts[index * 2 +0] = fx;
///< 在这里人为将坐标加100是为了让图像下移,避免扭曲后被屏幕遮挡
orig[index * 2 + 1] = verts[index * 2 + 1] = fy + 100;
index += 1;
}
}
}
/**
* @fun 波动
* 改变纵坐标的值,横坐标不变
*/
private void flagWavr()
{
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((float)i / WIDTH * 2 * Math.PI +
Math.PI * k);
verts[(j * (WIDTH + 1) + i) * 2 + 1] =orig[(j * WIDTH + i) * 2 + 1] +offsetY *A;
}
}
}
@Override
protected void onDraw(Canvas canvas) {
// TODO Auto-generated method stub
flagWavr();
k += 0.1F;
canvas.drawBitmapMesh(bm, WIDTH, HEIGHT, verts, 0, null, 0, null);
invalidate();
// canvas.drawBitmap(bm, 0, 0, new Paint());
}
}