Search code examples
androidlinear-gradientsandroid-jetpack-compose

Android Compose - custom linearGradient with angle like GradientDrawable


How to custom Brush.linearGradient() with angle param, such as O, 45, 90, 135... or any angle other?

Thanks.


Solution

  • Setting any angle for LinearGradient seems is a good idea, but that needs too much work to do...

    And setting the angle such as 0, 45, 90, 135.. is relatively simple. With the method of Brush.linearGradient(...), you can combine the parameter start and end to make it.

    First see this function

            @Stable
            fun linearGradient(
                colors: List<Color>,
                start: Offset = Offset.Zero,
                end: Offset = Offset.Infinite,
                tileMode: TileMode = TileMode.Clamp
            )
    

    from the default parameter values (start, end), we can conclude default angle is 135. and how?

    start = Offset.Zero == Offset(0f, Float.POSITIVE_INFINITY)
    end = Offset.Infinite == Offset(Float.POSITIVE_INFINITY, Float.POSITIVE_INFINITY)
    
    
    

    from start to end in the Cartesian coordinates, we can see the direction is right down, so the angle is 135. So, we can conclude

    angle 0
    start = Offset(0f,0f)
    end = Offset(Float.INFINITY,0f)
    
    angle 45 
    start = Offset(0f, Float.POSITIVE_INFINITY)
    end = Offset(Float.POSITIVE_INFINITY, 0f)
    
    angle 90 
    start = Offset(0f, Float.POSITIVE_INFINITY)
    end = Offset(0f,0f)
    ... 
    ``