Android LinearLayout Gradient Background

前端 未结 10 1788
渐次进展
渐次进展 2020-12-02 04:20

I am having trouble applying a gradient background to a LinearLayout.

This should be relatively simple from what I have read but it just doesn\'t seem to work. For r

10条回答
  •  眼角桃花
    2020-12-02 04:41

    You can used a custom view to do that. With this solution, it's finished the gradient shapes of all colors in your projects:

    class GradientView(context: Context, attrs: AttributeSet) : View(context, attrs) {
    
        // Properties
        private val paint: Paint = Paint()
        private val rect = Rect()
    
        //region Attributes
        var start: Int = Color.WHITE
        var end: Int = Color.WHITE
        //endregion
    
        override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
            super.onSizeChanged(w, h, oldw, oldh)
            // Update Size
            val usableWidth = width - (paddingLeft + paddingRight)
            val usableHeight = height - (paddingTop + paddingBottom)
            rect.right = usableWidth
            rect.bottom = usableHeight
            // Update Color
            paint.shader = LinearGradient(0f, 0f, width.toFloat(), 0f,
                    start, end, Shader.TileMode.CLAMP)
            // ReDraw
            invalidate()
        }
    
        override fun onDraw(canvas: Canvas) {
            super.onDraw(canvas)
            canvas.drawRect(rect, paint)
        }
    
    }
    

    I also create an open source project GradientView with this custom view:

    https://github.com/lopspower/GradientView

    implementation 'com.mikhaellopez:gradientview:1.1.0'
    

提交回复
热议问题