Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scaling a Bitmap to fit in a canvas

Im trying to write a game on droid, the way i take care of different screen resolutions is i make a bitmap with a target resolution (320x480), make a canvas from it and draw all the elements on it using fixed coordinates, then i just draw this bitmap on the surfaceView canvas and it rescales on different screens. The problem is that when i draw things on my frame the bitmap gets out of bounds even if the frame is the same size as the bitmap. (The bitmap is 320x480 and it gets streched and doesnt fit on 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 the 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 tips on this ? PS If i just draw the bitmap directly to the SurfacView canvas it gets scaled perfectly.

like image 655
user924941 Avatar asked Nov 13 '11 22:11

user924941


1 Answers

I'm going to add to nycynik and nikmin's answers.

You can utilise the 'createScaledBitmap' function to scale the Bitmap to the size of the screen (well, the canvas). Try to make your Bitmap resource fairly high-res so that if it is used on a larger screen, it won't have ugly scaling artifacts.

like image 60
Rob K Avatar answered Oct 24 '22 22:10

Rob K