Android:canvas draw self-rotating bitmap

Source: Internet
Author: User

    • 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);
    • More communication

Android Development Alliance QQ Group: 272209595

Android:canvas draw self-rotating bitmap

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.