fun creGradientStrokeDrawable(
@ColorInt colors: IntArray,
radius: Float,
strokeWidth: Float,
@GradientDirection gradientDirection: Int,
@ColorInt bgColors: IntArray? = null,
): LayerDrawable {
val outRectRadius = floatArrayOf(radius, radius, radius, radius, radius, radius, radius, radius)
val strokeWidthRectF = RectF(strokeWidth, strokeWidth, strokeWidth, strokeWidth)
val innerRadius = radius - strokeWidth
val innerRectRadius = floatArrayOf(innerRadius, innerRadius, innerRadius, innerRadius, innerRadius, innerRadius, innerRadius, innerRadius)
val roundRectShape = RoundRectShape(outRectRadius, strokeWidthRectF, innerRectRadius)
val shaderFactory = object : ShapeDrawable.ShaderFactory() {
override fun resize(width: Int, height: Int): Shader {
return when (gradientDirection) {
GradientDirection.LEFT_TO_RIGHT -> {
LinearGradient(0f, 0f, width.toFloat(), 0f, colors, null, Shader.TileMode.CLAMP)
}
GradientDirection.TOP_TO_BOTTOM -> {
LinearGradient(0f, 0f, 0f, height.toFloat(), colors, null, Shader.TileMode.CLAMP)
}
else -> {
LinearGradient(0f, 0f, width.toFloat(), height.toFloat(), colors, null, Shader.TileMode.CLAMP)
}
}
}
}
val shapeDrawable = ShapeDrawable(roundRectShape)
shapeDrawable.shaderFactory = shaderFactory
if (bgColors == null) {
return LayerDrawable(arrayOf(shapeDrawable))
}
val bgFactory = object : ShapeDrawable.ShaderFactory() {
override fun resize(width: Int, height: Int): Shader {
return when (gradientDirection) {
GradientDirection.LEFT_TO_RIGHT -> {
LinearGradient(0f, 0f, width.toFloat(), 0f, bgColors, null, Shader.TileMode.CLAMP)
}
GradientDirection.TOP_TO_BOTTOM -> {
LinearGradient(0f, 0f, 0f, height.toFloat(), bgColors, null, Shader.TileMode.CLAMP)
}
else -> {
LinearGradient(0f, 0f, width.toFloat(), height.toFloat(), bgColors, null, Shader.TileMode.CLAMP)
}
}
}
}
// 创建填充背景色的 RoundRectShape
val backgroundShape = RoundRectShape(outRectRadius, null, null)
val backgroundDrawable = ShapeDrawable(backgroundShape)
backgroundDrawable.shaderFactory = bgFactory
// 使用 LayerDrawable 将背景和边框组合在一起
return LayerDrawable(arrayOf(backgroundDrawable, shapeDrawable))
}
创建渐变边框和渐变背景的drawable
最新推荐文章于 2026-07-30 16:20:18 发布

210

被折叠的 条评论
为什么被折叠?



