- Demand
In Surfaceview or normal view, in each drawing cycle (OnDraw), we not only need to update the position of the drawing bitmap object in view, but also want the bitmap to be able to self-rotate with its own center point.
- Solve
Using the canvas's Drawbitmap (Bitmap Bitmap,matrix matrix,paint Paint) method, the most important thing is to customize the Matrix.
The code is as follows:
/** * Draw self-rotating bitmap * * @param canvas * @param paint * @param bitmap * Bitmap Object * @param Rotation * Rotation degree * @param PosX * position in canvas Coordinates * @param posY */ Private void Drawrotatebitmap(Canvas canvas, paint paint, Bitmap Bitmap,floatRotationfloatPosX,floatPosY) {Matrix Matrix =NewMatrix ();intOffsetX = Bitmap.getwidth ()/2;intOffsetY = Bitmap.getheight ()/2; Matrix.posttranslate (-offsetx,-offsety); Matrix.postrotate (rotation); Matrix.posttranslate (PosX + offsetX, PosY + OffsetY); Canvas.drawbitmap (bitmap, matrix, paint); }
First, we'll move the bitmap half of the upper-left corner (half the XY) and then rotate the desired degree. And finally move the center back. Then move to position coordinates (POSX,POSY). Note that the coordinate (Posx,posy) is the point in the upper-left corner of the bitmap.
In addition, in order to make the rotation coherent, when the method is called:
0.1f * (new Random().nextInt(20));drawRotateBitmap(canvas, paint, bitmap, rotation, posX, posY);
Android Development Alliance QQ Group: 272209595
Android:canvas draw self-rotating bitmap