@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繪圖基礎詳解(附源碼下載)給我的提示。