0

Hi have a problem regarding rotation. I'm currently drawing a few Objects on a Canvas. Currently this 'Objects' are just Bitmaps. After computing the rotation and passing it inside a Matrix, I'm forced to create a new Bitmap to get it rotated. A small snippet will clearify this:

public void onDraw(Canvas canvas){
    mMatrix = new Matrix();
    mMatrix.postRotate(getRotation());
    Bitmap rotateBmp = Bitmap.createBitmap(mBitmap, 0, 0, mBitmap.getWidth(), mBitmap.getHeight(), mMatrix, true);
    canvas.drawBitmap(rotateBmp, mCoords.x -(mBitmap.getWidth() / 2), mCoords.y - ( mBitmap.getHeight() / 2), null);
    rotateBmp.recycle();
}

All I can do to save memory is calling recycle on the rotateBmp, and it will run most of the time correctly. Lets assume I have 10 Bitmap 'Objects' I want to rotate. That means I have to keep ten Bitmaps as 'sample' and create ten new Bitmaps in every draw-cycle plus an additional new Matrix (didn't find a way to 'reset' it). This sounds very weird to me. Is there another Way, to create 'something that can be drawn on a Canvas' on the fly (no XML), while keeping control of their rotation. Any Idea is very welcome. If its a View, a Drawable or another CustomClass doesn't matter. Maybe it is important that getRotation will be all the same for every "Something" that should be drawn. What is the best practice to do that?

4

2 回答 2

1

You can rotate the Canvas using canvas.rotate(float degrees)

public void onDraw(Canvas canvas) {
    canvas.drawBitmap(mBitmap, mCoords.x -(mBitmap.getWidth() / 2), mCoords.y - ( mBitmap.getHeight() / 2), null);
    canvas.rotate(getRotation());
}
于 2012-04-27T16:27:57.687 回答
1

With the great help of @Jason Robinson and how To Rotate Text in Canvas I figured out a Way, of how I can do it. Here is a short snippet, that will work:

Bitmap mBitmap = getResources()...
int xPositionOfBitmap
int yPositionOfBitmap
public void onDraw(Canvas canvas) {
    int bitmapCenterX = xPositionOfBitmap + (mBitmap.getWidth() / 2)
    int bitmapCenterY = yPositionOfBitmap + (mBitmap.getHeight() / 2)
    canvas.save()
    canvas.rotate(getRotation(),bitmapCenterX, bitmapCenterY)
    canvas.drawBitmap(mBitmap, xPositionOfBitmap, yPositionOfBitmap)
    canvas.restore()
}
于 2012-04-30T09:37:13.333 回答