问题描述
看看我下面的代码.
ShapeDrawable shapeDrawable = new ShapeDrawable(new RectShape());
shapeDrawable.getPaint().setColor(Color.parseColor("#5a2705"));
shapeDrawable.getPaint().setStyle(Style.STROKE);
shapeDrawable.getPaint().setAntiAlias(true);
shapeDrawable.getPaint().setStrokeWidth(2);
shapeDrawable.getPaint().setPathEffect(new CornerPathEffect(10));
我将此作为背景应用到我的 LinearLayout
,但边缘不平滑.我该如何解决这个问题?
I am applying this as background to my LinearLayout
, but the edges are not smooth. How can I fix this?
这是它的外观截图.
推荐答案
使用以编程方式创建的可绘制形状作为视图背景会导致描边宽度的外半部分被裁剪掉(原因我不知道).仔细观察你的图像,你会发现你的笔触只有 1 像素宽,即使你要求 2.这就是为什么角落看起来很丑.如果您分别尝试更大的笔划和半径(例如 10 和 40),则这种效果会更加明显.
Using a programmatically-created shape drawable as a View background results in the outer half of your stroke width getting cropped off (for reasons I don't know). Look closely at your image and you'll see that your stroke is only 1 pixel wide, even though you requested 2. That is why the corners look ugly. This effect will be much more apparent if you try a bigger stroke and radius such as 10 and 40, respectively.
使用 XML drawable,它似乎没有这个问题,就像在 Harshit Jain 的回答中一样,或者如果您必须(或更喜欢)使用编程解决方案,请执行以下操作.
Either use an XML drawable, which doesn't seem to have this problem, like in Harshit Jain's answer, or do the following if you must (or prefer to) use a programmatic solution.
解决方案: 使用图层列表将矩形插入被裁剪的数量(笔画宽度的一半),如下所示:
Solution: Use a layer list to inset the rectangle by the amount that is being clipped (half the stroke width), like this:
float strokeWidth = 2;
ShapeDrawable shapeDrawable = new ShapeDrawable(new RectShape());
shapeDrawable.getPaint().setColor(Color.parseColor("#5a2705"));
shapeDrawable.getPaint().setStyle(Style.STROKE);
shapeDrawable.getPaint().setAntiAlias(true);
shapeDrawable.getPaint().setStrokeWidth(strokeWidth);
shapeDrawable.getPaint().setPathEffect(new CornerPathEffect(10));
Drawable[] layers = {shapeDrawable};
LayerDrawable layerDrawable = new LayerDrawable(layers);
int halfStrokeWidth = (int)(strokeWidth/2);
layerDrawable.setLayerInset(0, halfStrokeWidth, halfStrokeWidth, halfStrokeWidth, halfStrokeWidth);
然后使用 layerDrawable
作为您的背景.这是上面代码的结果的屏幕截图:
Then use the layerDrawable
as your background. Here is a screen shot of the result of the above code:
这篇关于圆角视图不平滑的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!