Circular gradient in android

后端 未结 7 921
灰色年华
灰色年华 2020-12-04 06:30

I\'m trying to make a gradient that emits from the middle of the screen in white, and turns to black as it moves toward the edges of the screen.

As I make a \"normal

7条回答
  •  清歌不尽
    2020-12-04 06:54

    You can also do it in code if you need more control, for example multiple colors and positioning. Here is my Kotlin snippet to create a drawable radial gradient:

    object ShaderUtils {
        private class RadialShaderFactory(private val colors: IntArray, val positionX: Float,
                                          val positionY: Float, val size: Float): ShapeDrawable.ShaderFactory() {
    
            override fun resize(width: Int, height: Int): Shader {
                return RadialGradient(
                        width * positionX,
                        height * positionY,
                        minOf(width, height) * size,
                        colors,
                        null,
                        Shader.TileMode.CLAMP)
            }
        }
    
        fun radialGradientBackground(vararg colors: Int, positionX: Float = 0.5f, positionY: Float = 0.5f,
                                     size: Float = 1.0f): PaintDrawable {
            val radialGradientBackground = PaintDrawable()
            radialGradientBackground.shape = RectShape()
            radialGradientBackground.shaderFactory = RadialShaderFactory(colors, positionX, positionY, size)
            return radialGradientBackground
        }
    }
    

    Basic usage (but feel free to adjust with additional params):

    view.background = ShaderUtils.radialGradientBackground(Color.TRANSPARENT, BLACK)
    

提交回复
热议问题