public class Main extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
MyView myView = new MyView(Main.this);
setContentView(myView);
}
// 自定义视图类
class MyView extends View {
private Bitmap bitmap;
private Matrix matrix = new Matrix();// Matrix 实例
private float angle = 0.0f;// Matrix 实例
private int w, h;// 位图宽和高
private float scale = 1.0f;// 缩放比例
private boolean isScale = false;// 判断缩放还是旋转
// 构造方法
public MyView(Context context) {
super(context);
bitmap = BitmapFactory.decodeResource(this.getResources(),
R.drawable.girl);// 获得位图
w = bitmap.getWidth();// 获得位图宽
h = bitmap.getHeight();// 获得位图高
this.setFocusable(true);// 使当前视图获得焦点
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
matrix.reset();// 重置Matrix
if (!isScale) {
matrix.setRotate(angle);// 旋转Matrix
} else {
matrix.setScale(scale, scale);// 缩放Matrix
}
Bitmap bitmap2 = Bitmap.createBitmap(bitmap, 0, 0, w, h, matrix,
true); // 根据原始位图和Matrix创建新视图
canvas.drawBitmap(bitmap2, matrix, null);// 绘制新视图
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
// 向左旋转
if (keyCode == KeyEvent.KEYCODE_DPAD_LEFT) {
isScale = false;
angle++;
postInvalidate();
}
// 向右旋转
if (keyCode == KeyEvent.KEYCODE_DPAD_RIGHT) {
isScale = false;
angle--;
postInvalidate();
}
// 放大
if (keyCode == KeyEvent.KEYCODE_DPAD_UP) {
isScale = true;
if (scale < 2.0)
scale += 0.1;
postInvalidate();
}
// 缩小
if (keyCode == KeyEvent.KEYCODE_DPAD_DOWN) {
isScale = true;
if (scale > 0.5)
scale -= 0.1;
postInvalidate();
}
return super.onKeyDown(keyCode, event);
}
}
}