Android - Setting background on canvas using PNG f

2019-08-24 17:09发布

I'm trying to set a .PNG file as background on Canvas in my app. I've made an image 480 x 800 and used this method:

canvas.drawBitmap(BitmapFactory.decodeResource(getResources(), 
                  R.drawable.image_1), 0, 0, null);

I've started an emulator (WVGA800) but my image looks greater than screen of the device.

How do I resize this image or what kind of methods should I use to make this image well-matched.

Secondly, is there any way to make backgrounds like this universal for devices with different screen resolutions?

Thank you in advance.

3条回答
Fickle 薄情
2楼-- · 2019-08-24 17:44

where did you put the image? if it's in the drawable or the drawable-mdpi , it will be larger than what you've told , since WVGA800 has a high density (hdpi) .

even if you put it on the drawable-hdpi folder , it will work for WVGA800 , but it might not show well on other devices , which have different resolutions and aspect ratio .

you need to handle the scaling and keeping of aspect ratio (if you wish) . otherwise , you will have the same problems on other devices.

查看更多
够拽才男人
3楼-- · 2019-08-24 17:50

The easiest way: declare static Bitmap in your class:

Bitmap bitmap;

setup the resized bitmap, for example you want resized bitmap to 100x100:

    private void initBitmap(){
            bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.Your_bitmap);
            bitmap = Bitmap.createScaledBitmap(bitmap, 100,100,true);
    }

and call method in constructor

查看更多
甜甜的少女心
4楼-- · 2019-08-24 17:54

Try this one ...

Set bitmap

Bitmap mFinalbitmap= BitmapFactory.decodeResource(getResources(), R.drawable.image_1);

Resize bitmap as per your width and height

mFinalbitmap= resizeImage(mFinalbitmap, width ,height);

Set Canvas of Bitmap

canvas.drawBitmap(mFinalbitmap, 0, 0, null);

Resize Function: As per maintain x and y of image

public Bitmap resizeImage(Bitmap image,int maxWidth, int maxHeight)
{
    Bitmap resizedImage = null;
    try {
        int imageHeight = image.getHeight();


        if (imageHeight > maxHeight)
            imageHeight = maxHeight;
        int imageWidth = (imageHeight * image.getWidth())
                / image.getHeight();

        if (imageWidth > maxWidth) {
            imageWidth = maxWidth;
            imageHeight = (imageWidth * image.getHeight())
                    / image.getWidth();
        }

        if (imageHeight > maxHeight)
            imageHeight = maxHeight;
        if (imageWidth > maxWidth)
            imageWidth = maxWidth;


        resizedImage = Bitmap.createScaledBitmap(image, imageWidth,
                imageHeight, true);
    } catch (OutOfMemoryError e) {

        e.printStackTrace();
    }catch(NullPointerException e)
    {
        e.printStackTrace();
    }
    catch (Exception e) {
        e.printStackTrace();
    }
    return resizedImage;
}
查看更多
登录 后发表回答