View 圆角设计 - litonghui/TechBlog GitHub Wiki

在Android 开发中设计View 的圆角问题很常见,但是或多或少会遇到绘制不准确的问题,提供两种方式给予参考:

一,XML shape

空心:
 <?xml version="1.0" encoding="UTF-8"?>
 <shape android:shape="rectangle"
     xmlns:android="http://schemas.android.com/apk/res/android">
   <corners android:radius="2dp" /> <!-- 四个角的角度 -->
   <!-- stroke为需要填充的边框,指定颜色及边框宽度  -->
   <stroke android:width="1dp" android:color="@color/color_green" />
 </shape>
实心
 <shape android:shape="rectangle"
     xmlns:android="http://schemas.android.com/apk/res/android">
   <corners android:radius="2dp" /> <!-- 四个角的角度 -->
   <!-- stroke为需要填充的边框,指定颜色及边框宽度  -->
   <solid android:width="1dp" android:color="@color/color_green" />
 </shape>
二,GradientDrawable
private GradientDrawable getGradientDrawable(boolean isSolid) {
 
    GradientDrawable drawable = new GradientDrawable();
    drawable.setCornerRadius(Utils.dp2px(context, 2f));
    if (isSolid) {
        drawable.setColor(0xff333333);
    } else {
        drawable.setStroke(Utils.dp2px(context, 1f), 0xff333333);
    }
    drawable.setGradientType(GradientDrawable.RADIAL_GRADIENT);
    return drawable;
}
GradientDrawable 和 shape 设计方式相同,可以避免绘制过程中出现空心矩形圆角和边宽度不一致问题。
⚠️ **GitHub.com Fallback** ⚠️