Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Devide independence for Canvas class drawing primitives

Tags:

android

The Android Canvas class supports a rich set of drawing primitives - circles, lines, etc. I have an app that uses these to chart some statistical data.

After reading the description on http://developer.android.com/reference/android/graphics/Canvas.html#drawLine%28float,%20float,%20float,%20float,%20android.graphics.Paint%29 . . . I was unclear what units the coordinates were in or how to make them device / resolution independent.

What units are these in and what's "best practice" for drawing lines and circles and rectangles that work on lots of different screen sizes and resolutions? Thanks in advance.

like image 831
Peter Nelson Avatar asked Feb 05 '11 17:02

Peter Nelson


1 Answers

Android documentation says "The unit for location and dimensions is the pixel". After experimenting for a while I found out that prior to version 2.0 the unit was the pixel. But starting from 2.0 the unit is most likely the dip (device-independent pixel).

For the following code:

Paint paint = new Paint();
paint.setColor(Color.RED);
paint.setStyle(Paint.Style.STROKE);
paint.setStrokeWidth(0);
canvas.drawRect(new Rect(1, 1, 319, 319), paint);

I get the same size square matching the width of the screen on 320x480, 480x800, and 240x320 emulators with android 2.0+.

This discovery allowed me to solve the problem: 1-pixel vertical lines on a large screen are sometimes 2-pixel wide. Set stroke width to 0 to draw 1-pixel lines independent of the screen size.

Edit

After getting more experience with Android, I need to correct my conclusions. Actually there is an attribute "android:anyDensity" in the "supports-screens" tag of the AndroidManifest.xml. This attribute is true by default. When it's true, the unit of measure is dp, otherwise it's a pixel.

like image 200
Viachaslau Tysianchuk Avatar answered Nov 15 '22 20:11

Viachaslau Tysianchuk