How can I scale my bitmap in Android based on the

2019-07-23 04:22发布

问题:

I want to be able to scale my image based on the screen size. In a normal java applet I would do something like the following....

int windowWidth = 1280;
int windowHeight = 720;

Image image;

public void paint(Graphics g)
{
    g.drawImage(image, x, y, windowWidth / 4, windowHeight / 16, null);
}

I've been searching for an answer for a while and everything I find seems to turn up some weird result. From what I read I might need to do something with Resolution Independent Pixels but I'm not %100 sure.

The thing I am trying to avoid is having to create a whole new set of images and icons just for different screen densities. The method I showed above works for resizing desktop apps without a problem.

Edit:

This is what I have been using to draw an image in android.

Matrix matrix = new Matrix();
Bitmap image;

Constuctor....()
{
image = BitmapFactory.decodeResource(context.getResources(), R.drawable.play);
}

public void render(Canvas c)
{
    c.drawBitmap(image, matrix, null);
}

回答1:

Hi see thsi question I have posted scale bitmap

If you are using canvas get the width and height of the canvas. or if you want to have it formal normal layouts then get the width and height by using

DisplayMetrics metrics = new DisplayMetrics();
 getWindowManager().getDefaultDisplay().getMetrics(metrics);
 dispWidth=metrics.widthPixels;
 dispheight=metrics.heightPixels;

and then scale our bitmap according to your requirement like this. In this I Have to have 8 bricks so I have taken the width by dividing with the Number of columns

      String strwidth=String.valueOf(((float)(bmp.getWidth())/NO_COLUMNS));
        if(strwidth.contains("."))
        {
            scalebit=Bitmap.createScaledBitmap(bmp, (int)(Math.ceil(((float)bmp.getWidth())/NO_COLUMNS))*NO_COLUMNS, bmp.getHeight(), true);
        }
        else
        {
            scalebit=bmp;
        }