Canvas绘制圆角矩形时的圆角粗边问题

xiaoxiao2021-02-28  64

@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ViewCompat.setBackground(findViewById(R.id.text_view), createCircleRect(5, Color.RED, 30)); } public ShapeDrawable createCircleRect(final int strokeWidth, final int strokeColor, final int radius) { Shape shape = new Shape() { @Override public void draw(Canvas canvas, Paint paint) { paint.setStyle(Paint.Style.STROKE); paint.setStrokeWidth(strokeWidth); paint.setColor(strokeColor); RectF rectf= new RectF(0, 0, getWidth(), getHeight()); canvas.drawRoundRect(rectf, radius, radius, paint); } }; return new ShapeDrawable(shape); }

使用以上代码绘制TextView的背景Shape,会发现,四个圆角的线宽要大于四边直线线宽。如图:

出现这种问题的原因是,使用Style.Stroke绘制粗线,基准线在中线,stroke边由中线向内外扩展。以上代码直接以矩形的最外一圈作为基准线,导致直线边只能绘制向里的一半线宽。所以Shape中的draw方法应该做如下修改:

Shape shape = new Shape() { @Override public void draw(Canvas canvas, Paint paint) { paint.setStyle(Paint.Style.STROKE); paint.setStrokeWidth(strokeWidth); paint.setColor(strokeColor); int d = strokeWidth / 2; RectF rectF= new RectF(d, d, getWidth()- d, getHeight()- d); canvas.drawRoundRect(rectF, radius, radius, paint); } };

这样显示的圆角矩形就正常了:

感谢文章:Android中Canvas绘图基础详解(附源码下载)给我的提示。

转载请注明原文地址: https://www.6miu.com/read-78511.html

最新回复(0)