Android - move inside the path

I want to draw a shape defined using Path with a stroke width of 5, where the entire stroke is inside the Path, and not half of the stroke inside and half outside.

Thanks,

Charles

+7
source share
3 answers

It does not seem to be able to control the position of the impact (i.e., inside, in the center or outside). For more information, refer to: Positioning the barcode width of Android Paint

My solution compensates for the stroke width when drawing, for example

final RectF rectF = new RectF(halfStrokeWidth, halfStrokeWidth, width - halfStrokeWidth, height - halfStrokeWidth); canvas.drawRoundRect(rectF, roundX, roundY, paint); 
+1
source

You can use the CornerPathEffect class for reference! We give an example of a rounded shape.

When drawing a background with a radius using the canvas.drawRoundRect () method and Style.FILL color sets, you can get a round rectangle shape. And then, by drawing a round rectangular frame on it with Style.STROKE and the width of the paint settings, using the same method, you can get the border.

The code:

 mBackgroundRectF.set(0, 0, mWidth, mHeight); canvas.drawRoundRect(mBackgroundRectF, mRadius, mRadius, mBackgroundPaint); // edge ajustment because paint stroke style is center align float edge = mBorderWidth / 2; mBackgroundRectF.set(edge, edge, mWidth - edge, mHeight - edge); canvas.drawRoundRect(mBackgroundRectF, mRadius, mRadius, mBorderPaint); 

Now it seems this is not the one I need, which has an offset between the background and the border:

before

Try CornerPathEffect:

 mBackgroundRectF.set(0, 0, mWidth, mHeight); canvas.drawRoundRect(mBackgroundRectF, mRadius, mRadius, mBackgroundPaint); // edge ajustment because paint stroke style is center align float edge = mBorderWidth / 2; mBackgroundRectF.set(edge, edge, mWidth - edge, mHeight - edge); // use CornerPathEffect and then use drawRect() method mBorderPaint.setPathEffect(new CornerPathEffect(mRadius / 2)); canvas.drawRect(mBackgroundRectF, mBorderPaint); 

Now it looks right:

after

+1
source

Use Canvas#clipPath(Path, Op) . But keep in mind that clipping path support in hardware accelerated canvas was removed in Android 3.0 and re-introduced in 4.3 . There was apparently a workaround for 3.0-4.2, but I have no way to test it.

+1
source

All Articles