Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What unit of measure does Paint.setStrokeWidth() use?

Tags:

android

What unit of measure does Paint.setStrokeWidth() use and do I need to scale this value based on the current screen density?

It's a float value so I know it's not a number of pixels. It must be relative to something.

This is all the documentation says as of this writing:

Set the width for stroking. Pass 0 to stroke in hairline mode. Hairlines always draws a single pixel independent of the canva's matrix.

like image 937
Bryan Bedard Avatar asked Jan 25 '11 03:01

Bryan Bedard


3 Answers

The stroke width is defined in pixels (yes it's a float, and there's no problem with using fractions of pixels :)

like image 76
Romain Guy Avatar answered Oct 15 '22 18:10

Romain Guy


setStrokeWidth uses pixels.

So to convert you dps to pixels for painting:

int dpSize =  10;
DisplayMetrics dm = getResources().getDisplayMetrics() ;
float strokeWidth = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dpSize, dm);
paint.setStrokeWidth(strokeWidth);
like image 20
AmeyaB Avatar answered Oct 15 '22 18:10

AmeyaB


One thing to keep in mind if you're attempting to onDraw your own "canvas border" is that even the stroke is clipped. So

paint.style = Paint.Style.STROKE
rect.set(0, 0, width, height)
paint.strokeWidth = 10F
canvas.drawRect(rect, paint)

will result in a "border" that is only 5F wide. This is due to the stroke being centered over the rect, which in this case is the edge of the canvas - resulting in half of it actually being clipped as it's outside the canvas.

To fix this, simply multiply your desired boarder thickness by 2. [In the example above, you'd set strokeWidth = 20F and you'd "see" a stroke of 10F.]

like image 3
Free Dorfman Avatar answered Oct 15 '22 19:10

Free Dorfman