美文网首页
Android 使用 LinearGradient 实现对角线颜

Android 使用 LinearGradient 实现对角线颜

作者: 卖炭少年炭治郎 | 来源:发表于2019-10-14 14:53 被阅读0次

    Android 使用 LinearGradient 实现对角线颜色渐变

    package com.demo.lib.view
    
    import android.content.Context
    import android.graphics.*
    import android.util.AttributeSet
    import android.util.Log
    import android.widget.FrameLayout
    import com.okay.lib.R
    
    /**
     * Create by shadow
     * 负责给view或是viewG添加渐变背景色
     *
     *  //Avoid object allocations during draw/layout operations (preallocate and reuse instead),意为避免在绘制/布局中去实例化对象。
    @SuppressLint("DrawAllocation")
     */
    class GradientViewGroup @JvmOverloads constructor(
        context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0
    ) : FrameLayout(context, attrs, defStyleAttr) {
    
        private val paint: Paint = Paint()
    
        private val rect :RectF = RectF()
    
        /**
         * 圆角
         */
        private val radius = 10F
    
        private var linearGradient: LinearGradient? = null
    
        init {
            paint.isAntiAlias = true
            Log.d("GradientViewGroup", "measuredWidth = $measuredWidth")
        }
    
        override fun dispatchDraw(canvas: Canvas) {
            super.dispatchDraw(canvas)
            linearGradient = LinearGradient(
                0F,
                0F,
                measuredWidth.toFloat(),
                measuredHeight.toFloat(),
                resources.getColor(R.color.colorAccent),
                resources.getColor(R.color.colorPrimary),
                Shader.TileMode.CLAMP
            )
            rect.set(0F, 0F, measuredWidth.toFloat(), measuredHeight.toFloat())
            paint.shader = linearGradient
            Log.d("GradientViewGroup", "measuredWidth = $measuredWidth")
    //        canvas.drawRect(rect, paint)
            canvas.drawRoundRect(rect,radius,radius,paint)
        }
    }
    
    
    
    
    
    
    
    
    
    
    
    
    

    相关文章

      网友评论

          本文标题:Android 使用 LinearGradient 实现对角线颜

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