Draw a scaled bitmap to the canvas?

前端 未结 2 1867
轻奢々
轻奢々 2021-02-05 10:15

The following code defines my bitmap:

Resources res = context.getResources();

    mBackground = BitmapFactory.decodeResource(res,
            R.drawable.bg2);

         


        
相关标签:
2条回答
  • 2021-02-05 11:10

    To draw the scaled bitmap you want save your scaled bitmap in a field somewhere (here called mScaled) and call:

        c.drawBitmap(mScaled,0,0,null);
    

    in your draw method (or wherever you call it right now).

    0 讨论(0)
  • 2021-02-05 11:17

    Define a new class member variable: Bitmap mScaledBackground; Then, assign your newly created scaled bitmap to it: mScaledBackground = scaled; Then, call in your draw method: c.drawBitmap(mScaledBackground, 0, 0, null);

    Note that it is not a good idea to hard-code screen size in the way you did in your snippet above. Better would be to fetch your device screen size in the following way:

    int width = getWindowManager().getDefaultDisplay().getWidth();
    int height = getWindowManager().getDefaultDisplay().getHeight();
    

    And it would be probably better not to declare a new bitmap for the only purpose of drawing your original background in a scaled way. Bitmaps consume a lot of precious resources, and usually a phone is limited to a few mb of bitmaps you can load before your app ungracefully fails. Instead you could do something like this:

    Rect src = new Rect(0,0,bitmap.getWidth()-1, bitmap.getHeight()-1);
    Rect dest = new Rect(0,0,width-1, height-1);
    c.drawBitmap(mBackground, src, dest, null);
    
    0 讨论(0)
提交回复
热议问题