Search code examples
javaandroidbitmapandroid-canvasandroid-bitmap

How to make images on Bitmap smaller?


I am trying to build a simple game on android and while setting the background image and other image assets on my main screen it is appearing too big as shown in the below image.

enter image description here

The actual size of the image is 1920x1080 and I want it to fit my screen like the image shown below:

enter image description here

The code for I have used is:

public class PoliceView extends View {

private Bitmap police;
private Bitmap background;
private Paint scorePaint = new Paint();
private Bitmap life[] = new Bitmap[2];

public PoliceView(Context context) {
    super(context);

    police = BitmapFactory.decodeResource(getResources(),R.drawable.police);
    background = BitmapFactory.decodeResource(getResources(),R.drawable.gamebackground);
    

    scorePaint.setColor(Color.BLACK);
    scorePaint.setTextSize(70);
    scorePaint.setTypeface(Typeface.DEFAULT_BOLD);
    scorePaint.setAntiAlias(true);

    life[0] = BitmapFactory.decodeResource(getResources(),R.drawable.heart);
    life[1] = BitmapFactory.decodeResource(getResources(),R.drawable.brokenheart);

}

@Override
protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);

    //The order of draw matters as objects are drawn in this same order
    canvas.drawBitmap(background,0,0,null);
    canvas.drawBitmap(police, 0, 0, null);
    canvas.drawText("Score:",20, 60, scorePaint);
    //Three lives for the police
    canvas.drawBitmap(life[0],580, 10, null);
    canvas.drawBitmap(life[0],680, 10, null);
    canvas.drawBitmap(life[0],780, 10, null);
}}

How can I resize the images to fit the screen??


Solution

  • i use this code for resize image

            Bitmap tmp = BitmapFactory.decodeFile(mPath);
            ResizeWidth = (int) (your size);
            ResizeHeight = (int) (your size);
        
    
        Bitmap bitmap = Bitmap.createBitmap(ResizeWidth, ResizeHeight, Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(bitmap);
    
    
        Bitmap scaled = Bitmap.createScaledBitmap(tmp, ResizeWidth, ResizeHeight, true);
        int leftOffset = 0;
        int topOffset = 0;
        canvas.drawBitmap(scaled, leftOffset, topOffset, null);