Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save Saravana2/66c63665b2242f4f3645f6db4d984288 to your computer and use it in GitHub Desktop.
Save Saravana2/66c63665b2242f4f3645f6db4d984288 to your computer and use it in GitHub Desktop.
Generate linear gradient dynamically
import android.graphics.drawable.GradientDrawable
import java.lang.IllegalArgumentException
/**
* Created by saravanan on 21/02/19.
*/
object GradientUtils{
enum class GradientDegree{
/** draw the gradient from the top-left to the bottom-right */
DEGREE_315,
/** draw the gradient from the top to the bottom */
DEGREE_270,
/** draw the gradient from the top-right to the bottom-left */
DEGREE_225,
/** draw the gradient from the right to the left */
DEGREE_180,
/** draw the gradient from the bottom-right to the top-left */
DEGREE_135,
/** draw the gradient from the bottom to the top */
DEGREE_90,
/** draw the gradient from the bottom-left to the top-right */
DEGREE_45,
/** draw the gradient from the left to the right */
DEGREE_0,
}
fun getGradientColor(colors: IntArray,orientation: GradientDegree=GradientDegree.DEGREE_270):GradientDrawable{
return getGradientColor(cornerRadius = 0,colors = colors,orientation = orientation)
}
fun getGradientColor(cornerRadius:Int, colors :IntArray,orientation:GradientDegree):GradientDrawable{
if (colors.size>1){
val orientationTemp:GradientDrawable.Orientation=when(orientation){
GradientDegree.DEGREE_315->{ GradientDrawable.Orientation.TL_BR}
GradientDegree.DEGREE_270->{ GradientDrawable.Orientation.TOP_BOTTOM}
GradientDegree.DEGREE_225->{ GradientDrawable.Orientation.TR_BL}
GradientDegree.DEGREE_180->{ GradientDrawable.Orientation.RIGHT_LEFT}
GradientDegree.DEGREE_135->{ GradientDrawable.Orientation.BR_TL}
GradientDegree.DEGREE_90->{ GradientDrawable.Orientation.BOTTOM_TOP}
GradientDegree.DEGREE_45->{ GradientDrawable.Orientation.BL_TR}
GradientDegree.DEGREE_0->{ GradientDrawable.Orientation.LEFT_RIGHT}
}
val gradientDrawable=GradientDrawable(orientationTemp, colors)
gradientDrawable.cornerRadius=cornerRadius.toFloat()
return gradientDrawable
}
else{
throw IllegalArgumentException("Needs 2 or more number of color for create gradient color")
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment