Android2D move, rotate with Matrix
What should we do to move or rotate shape on canvas?
We have Matrix.
Matrix represents position, rotation of Bitmap or other shapes.
After changing this Matrix, and redraw(invalidate())
This Matrix is 3 x 3.(Android Developers )
Sample
View
public class DrawBitmapView extends View { private Paint paint; private Bitmap img; private Matrix matrix; public DrawBitmapView ( Context context ) { super(context); paint = new Paint(Paint.ANTI_ALIAS_FLAG); img = BitmapFactory.decodeResource(context.getResources(), R.drawable.mikasa); matrix = new Matrix(); } @Override protected void onDraw ( Canvas canvas ) { canvas.drawColor(Color.BLACK); canvas.drawBitmap(img, matrix, paint); } public void translateB( float dx, float dy ) { matrix.postTranslate(dx, dy); invalidate(); } public void scaleB ( float sx, float sy ) { matrix.postScale(sx, sy); invalidate(); } public void rotateB ( float degrees ) { matrix.postRotate(degrees); invalidate(); } public void skewB ( float kx, float ky ) { matrix.postSkew(kx, ky); invalidate(); } }
Activity
public class MainActivity extends Activity { DrawBitmapView bView; @Override protected void onCreate ( Bundle savedInstanceState ) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); bView = new DrawBitmapView(this); bView.setClickable(true); bView.setOnClickListener(new OnClickListener() { @Override public void onClick ( View v ) { bView.translateB(30, 30); } }); addContentView(bView, new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT)); } }
Add click event. When you click, move view.
Hi there! Would you mind if I share your blog with my zynga group? There’s a lot of people that I think would really enjoy your content. Please let me know. Thank you