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

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.



Solution 1:[1]

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);

Solution 2:[2]

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.]

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 ggorlen
Solution 2