使用drawBitmapMesh扭曲图片
2014-03-03 13:37
597 查看
实例
MainActivity.java
package com.example.drawbitmapmesh;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.view.Menu;
import android.view.MotionEvent;
import android.view.View;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(new MyView(MainActivity.this));
}
public class MyView extends View{
private Bitmap bitmap;
//指定图片横向,纵向被划分为20个格
private final int WIDTH=20;
private final int HEIGHT=20;
//定义顶点数量
private final int COUNT=(WIDTH+1)*(HEIGHT+1);
//定义一个数组,保存Bitmap上的21*21个点的坐标
private final float[] verts=new float[COUNT*2];
//顶一个数组,记录Bitmap未被扭曲之前的坐标
private final float[] orig=new float[COUNT*2];
public MyView(Context context) {
super(context);
bitmap=BitmapFactory.decodeResource(getResources(), R.drawable.my_img);
//获取图片的宽度和高度
float imageWidth=bitmap.getWidth();
float imageHeight=bitmap.getHeight();
int index=0;
for(int x=0;x<=WIDTH;x++){
float fx=(imageWidth/WIDTH)*x;
for(int y=0;y<=HEIGHT;y++){
float fy=(imageHeight/HEIGHT)*y;
orig[index*2+0]=verts[index*2+0]=fx;
orig[index*2+1]=verts[index*2+1]=fy;
index+=1;
}
}
setBackgroundColor(Color.WHITE);
}
//根据触摸位置计算verts数组里各元素的值
private void warp(float cx,float cy){
for(int i=0;i<COUNT*2;i+=2){
//获取触摸点和原始坐标x,y的距离
float dx=cx-orig[i];
float dy=cy-orig[i];
//计算触摸点和其他原始点的距离
float dd=dx*dx+dy*dy;
float d=(float) Math.sqrt(dd);
//计算扭曲度,距离当前点(cx,cy越远)扭曲度越小
float pull=200/d;
if(pull>=1){
verts[i+0]=cx;
verts[i+1]=cy;
}
else{
//控制各顶点向触摸事件发生偏移
verts[i+0]=orig[i+0]+dx*pull;
verts[i+1]=orig[i+1]+dy*pull;
}
}
invalidate();
}
@Override
protected void onDraw(Canvas canvas) {
//对Bitmap按verts数组进行扭曲
canvas.drawBitmapMesh(bitmap, WIDTH, HEIGHT, verts, 0, null, 0, null);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
//调用wrap方法,根据触摸屏时间的坐标来扭曲verts数组
warp(event.getX(), event.getY());
return true;
}
}
}
相关文章推荐
- 使用 drawBitmapMesh 扭曲图片
- 使用canvas.drawBitmapMesh扭曲图像
- drawBitmapMesh扭曲图片
- Android 图片特效处理:drawBitmapMesh——图像扭曲+动感
- 初学Android,图形图像之使用drawBitmapMesh扭曲图像(三十二)
- android中Canvas使用drawBitmap绘制图片
- 浪起来!使用 drawBitmapMesh 实现仿真水波纹效果
- Android Canvas使用drawBitmap绘制图片
- android中Canvas使用drawBitmap绘制图片
- Android:使用drawBitmapMesh方法产生水波(一)
- 使用 drawBitmapMesh 实现仿真水波纹效果
- Android Canvas的drawBitmapMesh实现扭曲图像
- android中Canvas使用drawBitmap绘制图片
- 使用drawBitmap绘制图片
- android中Canvas使用drawBitmap绘制图片
- android中Canvas使用drawBitmap绘制图片
- 使用canvas.drawBitmap画出的图片能否设置背景色??
- android中Canvas使用drawBitmap绘制图片
- Android 使用Canvas中的drawBitmap方法绘制拉伸的图片
- android中Canvas使用drawBitmap绘制图片