创建渐变边框和渐变背景的drawable

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))
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值