Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scaling and translating a bitmap in android

I am trying to sale a bitmap and translating it at each step.

If we look at the following code, I am drawing an image, translating and scaling it and then performing the same operations in reverse so as to get the original configuration back. But after applying the operations, I do get the original scaled image (scale factor 1) but the image is translated t a different position.

Could you please point out the correct method do so ? (In the example above, how do I reach the original configuration? )

 protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        Matrix matrix = new Matrix();

        scale = (float)screenWidth/201.0f;
        matrix.setTranslate(-40, -40);
        matrix.setScale(scale, scale);

        canvas.drawBitmap(bitMap, matrix, paint);

        //back to original
        canvas.drawColor(0, Mode.CLEAR);
        matrix.setScale(1.0f/scale, 1.0f/scale);
        matrix.setTranslate(40,40);
        canvas.drawBitmap(bitMap, matrix, paint);

    }
like image 316
User42 Avatar asked Sep 10 '13 01:09

User42


2 Answers

You should just use the Canvas methods for scaling and translating, that way you can then take advantage of the save() and restore() APIs to do what you need. For example:

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

    //Save the current state of the canvas
    canvas.save();

    scale = (float) screenWidth / 201.0f;

    canvas.translate(-40, -40);
    canvas.scale(scale, scale);
    canvas.drawBitmap(bitMap, 0, 0, paint);

    //Restore back to the state it was when last saved
    canvas.restore();

    canvas.drawColor(0, Mode.CLEAR);
    canvas.drawBitmap(bitMap, 0, 0, paint);
}
like image 159
Kevin Coppock Avatar answered Nov 01 '22 09:11

Kevin Coppock


I think the problem with your original code might be because of the way scale and translate use the point around which you scale/translate. IF you specify the correct pivot points in between/for the operations, things will be ok.

like image 44
MacD Avatar answered Nov 01 '22 08:11

MacD