Matrix实现旋转,缩放,平移
public class Main extends Activity {@Overridepublic 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);// 使当前视图获得焦点}@Overrideprotected void onDraw(Canvas canvas) {super.onDraw(canvas);matrix.reset();// 重置Matrixif (!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);// 绘制新视图}@Overridepublic 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);}}}
?