stroke inside path
I want to draw a shape as defined using Path with a stroke width of 5 where all of the stroke is inside the Path rather than half the stroke inside and half outside.
Thanks,
Carl
You can use CornerPathEffect class for help! Taking drawing a roundrect shape as an example.
While drawing a background color with radius using canvas.drawRoundRect() method and the paint sets Style.FILL, you can get a round rect shape. And then drawing a round rect border on it with Style.STROKE and width of paint's setting using the same method, you can get a 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 looks like, it isn't the one i want which has some offset between background and border:
before
Let's 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 correct:
after
Use Canvas#clipPath(Path, Op)
. But be aware that support for clipping to a path in a hardware accelerated canvas was removed in Android 3.0 and reintroduced in 4.3. There was apparently a workaround for 3.0-4.2, but I don't have a way to test it.
It seems it can not control the position of the stroke (ie, inside, center or outside). For more info refer to: Android Paint stroke width positioning
My solution is offset the stroke width while drawing eg,
final RectF rectF = new RectF(halfStrokeWidth, halfStrokeWidth, width - halfStrokeWidth, height - halfStrokeWidth);
canvas.drawRoundRect(rectF, roundX, roundY, paint);
链接地址: http://www.djcxy.com/p/13862.html
上一篇: 在堆栈/堆上创建对象?
下一篇: 在路径内的冲程