RecyclerView系列之二(下) ItemDecoration

当我们在getItemOffsets设定的ourRect区域画一个矩形时,

java 复制代码
private val LEFT_OFFSETS = 300  //这里暂时先直接写死300px
kotlin 复制代码
override fun onDraw(c: Canvas, parent: RecyclerView, state: RecyclerView.State) {
    super.onDraw(c, parent, state)
    val mLayoutManager = parent.layoutManager
    for (index in 0 until parent.childCount) {
        val child = parent.getChildAt(index)
        //这里绘制一个矩形,左右边距20px方便观察
        c.drawRect(
            0f + 20f,
            child.height.toFloat() * (index),
            LEFT_OFFSETS.toFloat() - 20f,
            child.height.toFloat() * (index) + child.height.toFloat(),
            mPaint
        )
    }
}

当我们给改变边距时,

kotlin 复制代码
override fun onDraw(c: Canvas, parent: RecyclerView, state: RecyclerView.State) {
        super.onDraw(c, parent, state)
        val mLayoutManager = parent.layoutManager
        for (index in 0 until parent.childCount) {
            val child = parent.getChildAt(index)
            //这里绘制一个矩形,左右边距20px方便观察
//            c.drawRect(
//                0f + 20f,
//                child.height.toFloat() * (index),
//                LEFT_OFFSETS.toFloat() - 20f,
//                child.height.toFloat() * (index) + child.height.toFloat(),
//                mPaint
//            )
            //这里绘制一个矩形,右边距超过所给outRect的20px看效果
            c.drawRect(0f, child.height.toFloat()*(index),
                LEFT_OFFSETS.toFloat()+20f, child.height.toFloat()*(index)+child.height.toFloat(), mPaint)
        }
    }

可以看到所绘制的矩形超出getItemOffsets方法设定的outRect范围的部分将是不可见的,这是因为在整个绘制流程中,先调用ItemDecoration的onDraw方法,再调用Item的onDraw方法,最后调用ItemDecoration的onDrawOver方法。 所以在ItemDecoration的onDraw函数中绘制的内容时,当超出边界,会被Item所覆盖,但是因为最后才调用onDrawOver方法,所以它绘制的内容不受outRect边界的限制,可以覆盖Item的区域显示。

绘制渐变蒙版,因为蒙版是浮在Item之上的,可以在onDrawOver中绘制。

kotlin 复制代码
override fun onDrawOver(c: Canvas, parent: RecyclerView, state: RecyclerView.State) {
    super.onDrawOver(c, parent, state)
    //画蒙版
    val temp = parent.getChildAt(0)
    val gradient = LinearGradient(
        parent.width / 2f, 0f, parent.width / 2f, temp.height * 4f,
        -0xffff01, 0x000000ff, Shader.TileMode.CLAMP
    )
    mPaint.shader = gradient
    c.drawRect(0f, 0f, parent.width.toFloat(), (temp.height * 4).toFloat(), mPaint)
}
相关推荐
帅次11 分钟前
Flutter DropdownButton 详解
android·flutter·ios·kotlin·gradle·webview
际宇人16 分钟前
移动端APP阿里云验证码2.0接入实录
android
.又是新的一天.30 分钟前
02_MySQL安装及配置
android·数据库·mysql
QING6181 小时前
Kotlin groupBy用法及代码示例
android·kotlin·源码阅读
QING6181 小时前
Kotlin getOrElse用法及代码示例
android·kotlin·源码阅读
QING6181 小时前
Kotlin getOrNull用法及代码示例
android·kotlin·源码阅读
QING6181 小时前
Kotlin getValue用法及代码示例
android·kotlin·源码阅读
QING6181 小时前
Kotlin getOrPut用法及代码示例
android·kotlin·源码阅读
QING6181 小时前
Kotlin groupingBy用法及代码示例
android·kotlin·源码阅读
祖师爷科技1 小时前
kotlin扩展函数的实现原理
android·kotlin