I am trying to implement a watch face where a bitmap image of a hand rotates about the center of the face on a canvas.
- Basically in the onDraw() method, I want to be able to put an image resource onto the canvas then rotate it rotate it every second.
- I have logic in place to trigger the rotation every second, I am not sure how to obtain the image resource and then rotate it.
Any help would be appriciated!
I recently needed to solve the bitmap rotation problem for an Android Wear watchface. The following onDraw code worked for me. Be sure your bitmaps are scaled before onDraw gets called:
and for scaling:
Note that the image sizes of my background and watch hand resources are all 480x480. That eliminates any need for translation to center, and (possibly) is easier on the battery.
I hope this is useful.
Basic steps:
Decode your bitmap from, for example, Resources, but there are other ways. (You would want to do this once when initializing the class, not on every draw cycle.):
Bitmap = mBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.watch_face);
Set up a
Matrix
insideonDraw
for the rotation. Something like:Matrix mMatrix = new Matrix(); mMatrix.setRotate (degreeOfRotation, mBitmap.getWidth()/2, mBitmap.getHeight()/2);
Draw the Bitmap using a method that takes in your Matrix:
canvas.drawBitmap(mBitmap, mMatrix, mPaint);
There are other details. Setting up
Paint
. You may find you need to use the Matrix'spostRotate
method instead. Etc. Etc. But this should be enough to you started Googling.In this certain situation (I guess you're trying to rotate bitmaps with Google watch face api) you should have in mind rules described in this brilliant post, and avoid using large bitmaps for watch hands. This means you'll have to specify vertical and horizontal margins. I used the solution posted by Jave here.
I gave up cropping the bitmap vertically, since it's much easier to rotate it this way, but it should be taken in consideration if you want to be in full compliance to the rules. It would be even better not to calculate
marginX
here. It may be done inonSurfaceChanged
, as described in the post mentioned above.