Matrix实现旋转,缩放,平移

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);
		}
	}
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值