简体   繁体   中英

Android - Fitting bitmap to screen

I have this project in which I have a bitmap bigger than the screen size. I want to resize it to fit the screen exactly. I have no titlebar, and I am in fullscreen mode. This is my non-working code:

public class ScopView extends View
{
    private Scop thescop;

    public ScopView(Context context, Scop newscop)
    {
        super(context);
        this.thescop = newscop;
    }

    @Override
    public void onDraw(Canvas canvas)
    {
        Bitmap scopeBitmap;
        BitmapFactory.Options bfOptions = new BitmapFactory.Options();
        bfOptions.inDither = false;
        bfOptions.inPurgeable = true;
        bfOptions.inInputShareable = true;
        bfOptions.inTempStorage = new byte[32 * 1024];

        scopeBitmap = BitmapFactory.decodeResource(getResources(),R.drawable.scope, bfOptions);
        scopeBitmap.createScaledBitmap(scopeBitmap, SniperActivity.Width, SniperActivity.Height, false);
        canvas.drawBitmap(scopeBitmap, SniperActivity.scopx, SniperActivity.scopy, null);
    }
}

While in here the createScaledBitmap method, I am using itself as the source, and some variables from an activity used to retrieve the window height and width from screen preferences.

You can use the below code to resize the bitmap.

int h = 320; // Height in pixels
int w = 480; // Width in pixels    
Bitmap scaled = Bitmap.createScaledBitmap(largeBitmap, h, w, true);

Also, you can use the below code snippet.

public Bitmap getResizedBitmap(Bitmap bm, int newHeight, int newWidth) {
    int width = bm.getWidth();
    int height = bm.getHeight();
    float scaleWidth = ((float) newWidth) / width;
    float scaleHeight = ((float) newHeight) / height;

    // Create a matrix for the manipulation
    Matrix matrix = new Matrix();

    // Resize the bit map
    matrix.postScale(scaleWidth, scaleHeight);

    // Recreate the new Bitmap
    Bitmap resizedBitmap = Bitmap.createBitmap(bm, 0, 0, width, height, matrix, false);

    return resizedBitmap;
}

This code is help to you try this

int REQ_WIDTH = 0;
int REQ_HEIGHT = 0;
REQ_WIDTH =imageView.getWidth();
vREQ_HEIGHT =imageView.getHeight();
mImageView.setImageBitmap(Bitmap.createScaledBitmap(BitmapFactory.decodeFile(imageURI, options), REQ_HEIGHT, REQ_WIDTH, true));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM