开发者

Devide independence for Canvas class drawing primitives

开发者 https://www.devze.com 2023-02-09 06:24 出处:网络
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.

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%28f开发者_如何学Goloat,%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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消