Android: draw an arc with gradient fill color

I want to draw an arc on canvas with a gradient fill. How can this be achieved?

+5
source share
2 answers

Hey, I stole it from here: Draw an arc with SweepGradient in Android

but it works fine, instead I used LinearGradient.

Shader gradient = new SweepGradient (0,getMeasuredHeight()/2, Color.RED, Color.WHITE); lightRed.setShader(gradient); canvas.drawArc(rectf, -90, 360, false, lightRed); 
+9
source

You can also use an array of colors and variable positions. For example, define 10 colors, one for every 10% of the progress:

 <color name="color_0">#3C3C3F41</color> <color name="color_10">#1AFF2323</color> <color name="color_20">#33FF2323</color> <color name="color_30">#4DFF2323</color> <color name="color_40">#66FF2323</color> <color name="color_50">#80FF2323</color> <color name="color_60">#99FF2323</color> <color name="color_70">#B3FF2323</color> <color name="color_80">#CCFF2323</color> <color name="color_90">#E6FF2323</color> <color name="color_100">#FFFF2323</color> 

Put all these colors in intArray colors as follows:

 var colors = intArrayOf( ContextCompat.getColor(context, R.color.color_0), ContextCompat.getColor(context, R.color.color_10), ContextCompat.getColor(context, R.color.color_20), ContextCompat.getColor(context, R.color.color_30), ContextCompat.getColor(context, R.color.color_40), ContextCompat.getColor(context, R.color.color_50), ContextCompat.getColor(context, R.color.color_60), ContextCompat.getColor(context, R.color.color_70), ContextCompat.getColor(context, R.color.color_80), ContextCompat.getColor(context, R.color.color_90), ContextCompat.getColor(context, R.color.color_100) ) 

Then determine the position. Positions vary from 0.0 to 1.0 (positions 0.1 correspond to color_10, positions 0.2 correspond to color_20, etc.)

 var positions = floatArrayOf(0.0f, 0.1f, 0.2f, 0.3f, 0.4f, 0.5f, 0.6f, 0.7f, 0.8f, 0.9f, 1.0f) 

Once we have determined the position, we can set the SweepGradient for our paint

 Shader gradient = new SweepGradient (0,getMeasuredHeight()/2, colors, positions); lightRed.setShader(gradient); 

Finally, we can paint our arc using our shader paint:

  canvas.drawArc(rectf, -90, 360, false, lightRed); 

The final effect in my own view:

enter image description here

0
source

Source: https://habr.com/ru/post/1390585/


All Articles