Android-Canvas使用技巧
最近项目涉及到多媒体这一块,因此对Canvas的使用技巧做一个总结,供以后查询。下面是一个Bitmap旋转的Demo:
package com.jony.canvas;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
public class MainActivity extends Activity implements OnClickListener {
private final static int UPDATE = 0x1;
private Button rotate;
private static ImageView image;
// Handler应该使用static和final关键字进行限制,否则引用该对象的时候可能存在内存泄露
public static final Handler myHandler = new Handler() {
public void handleMessage(android.os.Message msg) {
switch (msg.what) {
case UPDATE:
Bitmap destmap = (Bitmap) msg.obj;
image.setImageBitmap(destmap);// 设置ImageView的显示内容
break;
default:
break;
}
};
};
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
rotate = (Button) findViewById(R.id.rotate);
image = (ImageView) findViewById(R.id.image);
rotate.setOnClickListener(this);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
@Override
public void onClick(View v) {
final Bitmap bitmap = BitmapFactory.decodeResource(getResources(),
R.drawable.image01);
new MyThread(bitmap).start();
}
class MyThread extends Thread {
private final static int ROTATE_DGREES = 45;
private Bitmap bitmap;
private Paint paint;
private Matrix matrix;
public MyThread(Bitmap bitmap) {
this.bitmap = bitmap;
matrix = new Matrix();
}
@Override
public void run() {
for (int i = 0; i < ROTATE_DGREES; i++) {
// 创建一个原图大小的空白Bitmap
Bitmap bg = Bitmap.createBitmap(bitmap.getWidth(),
bitmap.getHeight(), Config.ARGB_8888);
// 创建画布
Canvas canvas = new Canvas(bg);
//canvas.drawColor(0xFF000000);清屏处理
canvas.drawColor(0x00000000);// 设置画布为透明背景
// 达到图片旋转效果有两种方式:1、旋转Canvas 2、矩阵旋转
canvas.rotate(i);// 旋转角度
canvas.drawBitmap(bitmap, 0, 0, paint);
// 旋转矩阵
//matrix.setRotate(i);
//canvas.drawBitmap(bitmap, matrix, paint);
// image.setImageBitmap(bg);// 切忌,非UI线程不能处理UI信息
Message message = myHandler.obtainMessage();
message.obj = bg;
message.what = 0x1;
myHandler.sendMessage(message);
}
// 复位
Message message = myHandler.obtainMessage();
message.obj = bitmap;
message.what = 0x1;
myHandler.sendMessage(message);
}
}
}
代码比较简单,在此不做过多解释。
效果图:
代码下载地址: