Scaling a bitmap to fit on canvas

I'm trying to write a game on a droid, since I care about different screen resolutions, I make a bitmap with a target resolution (320x480), create a canvas from it and draw all the elements on it using fixed coordinates, then I just draw this bitmap on surfaceView canvas, and it scales on different screens. The problem is that when I draw things on my frame, the bitmap goes beyond the scope, even if the frame is the same size as the bitmap. (The bitmap is 320x480, and it is stretched and does not fit on the screen) Here is the code:

public class Graphics { private Bitmap frameBuffer, grid; private Canvas canvas; public Graphics(Context context) { frameBuffer = Bitmap.createBitmap(320, 480, Config.ARGB_8888); canvas = new Canvas(frameBuffer); grid = BitmapFactory.decodeResource(context.getResources(), R.drawable.grid); } public Bitmap present() { canvas.drawColor(Color.WHITE); canvas.drawBitmap(grid, 0, 0, null); return frameBuffer; } 

and SurfaceView class:

 public class GameView extends SurfaceView implements Runnable { private SurfaceHolder holder; private Boolean running; private Thread renderThread; private Graphics graphics; public GameView(Context context, Graphics graphics) { super(context); this.holder = getHolder(); this.graphics = graphics; } public void resume() { running = true; renderThread = new Thread(this); renderThread.start(); } public void run() { Rect dstRect = new Rect(); while (running) { if (!holder.getSurface().isValid()) continue; Bitmap frameBuffer = graphics.present(); Canvas canvas = holder.lockCanvas(); canvas.getClipBounds(dstRect); canvas.drawBitmap(frameBuffer, null, dstRect, null); holder.unlockCanvasAndPost(canvas); } } public void pause() { running = false; while (true) { try { renderThread.join(); break; } catch (InterruptedException e) { // retry } } } 

}

can anyone give some advice on this? PS If I just draw a bitmap directly on the SurfacView canvas, it scales well.

+6
source share
1 answer

I am going to add nycynik and nikmin to the answers.

You can use the createScaledBitmap function to scale the bitmap to fit the screen (well, canvas). Try to make the Bitmap resource high enough so that if it is used on a large screen, it will not have ugly artifacts of scaling.

+3
source

Source: https://habr.com/ru/post/901399/


All Articles