美文网首页读书点点
RecycleView渐变色分割线(ItemDecoration

RecycleView渐变色分割线(ItemDecoration

作者: 寻水的鱼Chock | 来源:发表于2022-10-25 16:02 被阅读0次
效果预览
渐变色分割线.png
实现

Item中间,宽度1dp,颜色从上到下#00FEDCCD -> #FFF7BEA5 -> #00FEDCCD渐变的分割线(利用着色器[Shader]实现颜色渐变)

class GradientItemDecoration : RecyclerView.ItemDecoration() {

    var mPaint: Paint = Paint().apply {
        isAntiAlias = true
    }

    //分割线渐变(从上到下)
    val colors = intArrayOf(Color.parseColor("#00FEDCCD"),Color.parseColor("#FFF7BEA5"),Color.parseColor("#00FEDCCD"))
    val positions = floatArrayOf(0f, 0.5f, 1f)

    override fun onDrawOver(c: Canvas, parent: RecyclerView, state: RecyclerView.State) {
        super.onDrawOver(c, parent, state)
        val childCount = parent.childCount
        for (position in 0 until childCount - 1) {
            val child = parent.getChildAt(position)
            val t = child.top + 4.dp()
            val b = child.bottom - 3.dp()
            val l = child.right.toFloat()
            val r = child.right + 1.dp()
            val w1 = child.right + 1.idp() / 2.0f
            val g = LinearGradient(w1, t, w1, b, colors, positions, Shader.TileMode.CLAMP)
            mPaint.shader = g
            c.drawRect(l, t, r, b, mPaint)
        }
    }

    override fun getItemOffsets(
        outRect: Rect,
        view: View,
        parent: RecyclerView,
        state: RecyclerView.State
    ) {
        super.getItemOffsets(outRect, view, parent, state)
        val cp = parent.getChildAdapterPosition(view)
        val itemCount = parent.adapter?.itemCount ?: 0
        if (cp != (itemCount - 1)) {
            outRect.right = 1.idp()
        }
    }
}
如果本文对你有帮助就点个赞支持下吧~~~

相关文章

网友评论

    本文标题:RecycleView渐变色分割线(ItemDecoration

    本文链接:https://www.haomeiwen.com/subject/rzxozrtx.html