I am having problems implementing this pattern. I have an custom view which has an image drawn on it. The user can take a corner of the image and drag it around, which results in rotation of the image.
In order to achieve this result I did the following: The bitmap is stored in an object which also has angle, x, y, centerX and centerY properties.
@Override
public boolean onTouchEvent(MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_MOVE:
int currentX = (int) event.getX();
int currentY = (int) event.getY();
double rotationAngleRadians = Math.atan2(currentX - image.getCenterX(), image.getCenterY() - currentY);
int rotationAngleDegrees = (int) Math.toDegrees(rotationAngleRadians);
rotateMatrix.setRotate(rotationAngleDegrees , image.getCenterX(), image.getCenterX());
.....
}
and then in onDraw I use the matrix to rotate the canvas
@Override
protected void onDraw(Canvas canvas) {
canvas.save(Canvas.MATRIX_SAVE_FLAG);
canvas.setMatrix(rotateMatrix);
canvas.drawBitmap(image.getBitmap, image.getX(), image.getY(), imagePaint);
canvas.restore();
}
The problem with this approach is the following: when The user starts to drag the button, the whole image "jumps up" 25 pixels and after that it starts to rotate. How can I fix this problem ?
It's possible that when you give the canvas your matrix, the canvas is disregarding a previous translation which was defined in its previous matrix.
A cleaner approach would be to just use the canvas.rotate(...)
method, instead of using matrixes. If you must use the matrix class, then make sure you're basing it on the original canvas.getMatrix()