I have implemented a long onDraw
method which draws a set of rectangles. The rectangles are too small and I want them to appear bigger. But unfortunately I can't change the rectangle coordinates because they are stored in a database. So is there any way I can zoom in the canvas using canvas.scale()
?
Asked
Active
Viewed 2.5k times
11
-
2"But unfortunately i cant change the rectangle coordinates becoz they are stored in a database" Why? you get the coordinates from the DB and multiply by whatever scale factor you need before drawRectangle(). – Simon Nov 12 '12 at 17:49
-
can i implement a zoom in function that way? – Ruby Nov 12 '12 at 17:58
-
1x = getValueFromDatabase(), y = getValueFromDatabase(), x=x*5;y=y*5; drawRectangle(x,y). What's wrong with something like that? My point is, why does having the values stored in a database stop you drawing the rectangles bigger? I don't get it. Of course you can change the rectangle coordinates. You can make them anything you want. – Simon Nov 12 '12 at 18:20
-
i know but as i have already have the data in the database and done drawing the map, i just need to know a method to zoom in the canvas or the view related to it :) – Ruby Nov 12 '12 at 18:45
-
If you want to target different devices, also check official suggestions to work with density of display: https://developer.android.com/guide/practices/screens_support.html#DensityConsiderations – Ped7g Oct 05 '16 at 13:31
1 Answers
27
I'm going to preface this answer by saying you will need to draw everything at 0,0 and then scale it, and finally translate it to behave properly.
Simply do the following in your onDraw method:
canvas.save();
canvas.translate(xValue, yValue);
canvas.scale(xScale, yScale)
/* draw whatever you want scaled at 0,0*/
canvas.restore();
xScale shrinks or stretches in the X direction, yScale shrinks or stretches in the Y direction.
1.0 is the default for these, so 2.0 would stretch it by double and 0.5 would shrink it by half.
Example:
canvas.save();
canvas.translate(50, 50);
canvas.scale(0.5f, 0.5f);
canvas.drawRect(0.0, 0.0, 5.0, 5.0, paint);
canvas.restore();
This will draw a rectangle with length 5.0, and width 5.0, scale it down to 2.5 for length and width, and then move it to (50, 50).
The result will be a rectangle drawn as if you did this:
canvas.drawRect(50.0, 50.0, 52.5, 52.5, paint);
I hope this helps!

Michael Dotson
- 519
- 3
- 7
-
but scale function behavior differently in different resolution devices. – zionpi Feb 24 '16 at 03:03
-
scale is not affected by the resolution, as we are just talking about pixels. – Michael Dotson Feb 24 '16 at 22:04
-
In case anyone will come here seeking solution for web (as I did =). Here is example code revised: `context.translate(50, 50); context.scale(0.5, 0.5); context.fillRect(0.0, 0.0, 5.0, 5.0);` – Nov 08 '17 at 10:57