GradientDrawable 是 Android 中用于定义各种形状和渐变效果的可绘制对象,它是 Drawable 的一个子类。通过 GradientDrawable,开发者可以创建矩形、椭圆形、线条和环形等形状,并为其设置纯色或渐变颜色。
GradientDrawable 支持以下几种主要形状类型:
<!-- res/drawable/circle_background.xml -->
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="oval">
<solid android:color="#FF5722" />
<size
android:width="100dp"
android:height="100dp" />
</shape>
然后在布局中使用:
<TextView
android:layout_width="100dp"
android:layout_height="100dp"
android:background="@drawable/circle_background"
android:text="AB"
android:textColor="#FFFFFF"
android:gravity="center"
android:textSize="24sp" />
Kotlin 示例:
val textView = TextView(context).apply {
layoutParams = ViewGroup.LayoutParams(100, 100)
text = "AB"
setTextColor(Color.WHITE)
gravity = Gravity.CENTER
textSize = 24f
background = GradientDrawable().apply {
shape = GradientDrawable.OVAL
setColor(Color.parseColor("#FF5722"))
}
}
val gradientDrawable = GradientDrawable(
GradientDrawable.Orientation.TOP_BOTTOM,
intArrayOf(Color.parseColor("#FF5722"), Color.parseColor("#FF9800"))
).apply {
shape = GradientDrawable.OVAL
gradientType = GradientDrawable.LINEAR_GRADIENT
cornerRadius = 50f // 对于圆形,半径应为宽度/高度的一半
}
textView.background = gradientDrawable
原因:视图的宽度和高度不相等,或者 cornerRadius 设置不当。
解决方案:
原因:颜色值过于接近或渐变方向设置不当。
解决方案:
原因:视图的 gravity 或文本对齐方式未正确设置。
解决方案:
android:gravity="center"
android:layout_gravity="center"
(在父布局中)原因:抗锯齿未启用或视图尺寸过小。
解决方案:
gradientDrawable.setAntiAlias(true)
val gradientDrawable = GradientDrawable().apply {
shape = GradientDrawable.OVAL
setColor(Color.WHITE)
setStroke(4, Color.BLUE) // 4px宽的蓝色边框
setSize(100, 100) // 设置固定尺寸
}
val textView = TextView(context).apply {
layoutParams = ViewGroup.LayoutParams(100, 100)
text = "AB"
setTextColor(Color.BLACK)
gravity = Gravity.CENTER
textSize = 24f
background = gradientDrawable
}
通过 GradientDrawable,开发者可以轻松创建各种自定义形状的视图,特别是圆形文本视图这种常见需求,既减少了资源文件数量,又提高了应用的性能和灵活性。
没有搜到相关的文章