如下程序开发了一个自定义View,该自定义View可以检测到用户的键盘事件,当用户单击手机的方向键时,该自定义View会用Matrix对绘制的图形进行旋转、倾斜变换。
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.drawable.BitmapDrawable;
import android.util.AttributeSet;
import android.view.KeyEvent;
import android.view.View;
public class MatrixTest extends View{
//初始化图片资源
private Bitmap bitmap;
//Matrix实例
private Matrix matrix = new Matrix();
//设置倾斜度
private float sx = 0.0f;
//位图宽和高
private int width;
private int height;
//缩放比例
private float scale = 1.0f;
//判断缩放还是旋转
private boolean isScale = false;
public MatrixTest(Context context, AttributeSet attrs) {
super(context, attrs);
// 获取位图
bitmap = ((BitmapDrawable)context.getResources().getDrawable(R.drawable.ic_launcher,null)).getBitmap();
//获得位图宽
width = bitmap.getWidth();
//获取位图高
height = bitmap.getHeight();
//使当前试图获得焦点
this.setFocusable(true);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
//重置
Matrix matrix.reset();
if(!isScale){
//旋转
Matrix matrix.setSkew(sx, 0);
}else{
//缩放
Matrix matrix.setScale(scale, scale);
}
//根据原始位图和Matrix创建新图片
Bitmap bitmap2 = Bitmap.createBitmap(bitmap, 0, 0, width, height, matrix, true);
//绘制新位图
canvas.drawBitmap(bitmap2, matrix, null);
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
switch (keyCode) {
//向左倾斜
case KeyEvent.KEYCODE_DPAD_LEFT:
isScale = false;
sx += 0.1;
postInvalidate();
break;
//向右倾斜
case KeyEvent.KEYCODE_DPAD_RIGHT:
isScale = false;
sx -= 0.1;
postInvalidate();
break;
//放大
case KeyEvent.KEYCODE_DPAD_UP:
isScale = true;
if(scale<2.0){
scale += 0.1;
}
postInvalidate();
break;
//缩小
case KeyEvent.KEYCODE_DPAD_DOWN:
isScale = true;
if(scale > 0.5){
scale -= 0.1;
}
postInvalidate();
break;
}
return super.onKeyDown(keyCode, event);
}
}