Android中實現圖片繞X軸、Y軸、Z軸翻轉可以使用matrix和camera,類似3D效果
具體參見代碼:
- public class FlipImgEffectView extends View {
-
- private Context context ;
- private Bitmap showBmp ;
- private Matrix matrix ; //作用矩陣
- private Camera camera ;
- private int deltaX , deltaY ; //翻轉角度差值
- private int centerX , centerY ; //圖片中心點
-
- public FlipImgEffectView(Context context) {
- super(context);
- this.context = context ;
- initData();
- }
-
- private void initData(){
- showBmp = BitmapFactory.decodeResource(context.getResources(), R.drawable.flower);
- centerX = showBmp.getWidth()/2 ;
- centerY = showBmp.getHeight()/2 ;
- matrix = new Matrix();
- camera = new Camera();
- }
-
- int lastMouseX ;
- int lastMouseY ;
- @Override
- public boolean dispatchTouchEvent(MotionEvent event) {
- int x = (int) event.getX();
- int y = (int) event.getY();
- switch(event.getAction()) {
- case MotionEvent.ACTION_DOWN:
- lastMouseX = x ;
- lastMouseY = y ;
- break;
- case MotionEvent.ACTION_MOVE:
- int dx = x - lastMouseX ;
- int dy = y - lastMouseY ;
- deltaX += dx ;
- deltaY += dy ;
- break;
- }
-
- invalidate();
- return true;
- }
-
- @Override
- protected void onDraw(Canvas canvas) {
-
- camera.save();
- //繞X軸翻轉
- camera.rotateX(-deltaY);
- //繞Y軸翻轉
- camera.rotateY(deltaX);
- //設置camera作用矩陣
- camera.getMatrix(matrix);
- camera.restore();
- //設置翻轉中心點
- matrix.preTranslate(-this.centerX, -this.centerY);
- matrix.postTranslate(this.centerX, this.centerY);
-
- canvas.drawBitmap(showBmp, matrix, null);
- }
-
- }
效果如圖: