How to set gradient style to paint object?

AndroidAndroid CanvasGradient

Android Problem Overview


The code for drawing an arrow with Style: Fill is given below:

paint.setColor(Color.parseColor("#bdc0dc"));
paint.setStyle(Style.FILL);
canvas.drawPath(arrowPath, paint);
paint.setColor(Color.BLACK);
paint.setStyle(Style.STROKE);
paint.setStrokeWidth(2);
canvas.drawPath(arrowPath, paint);

And the output I obtain is this :

enter image description here

Now what I want do is set style to Gradient(Style.gradient not present in android...) to obtain the arrow similar to the image given below :

enter image description here

How do i do it ? I tried adding style in style.xml but was unable to add gradient there as it accepts item as parameter..

Android Solutions


Solution 1 - Android

use the code below..

paint.setShader(new LinearGradient(0, 0, 0, getHeight(), Color.BLACK, Color.WHITE, Shader.TileMode.MIRROR));
    canvas.drawPath(arrowPath, paint);

Solution 2 - Android

If you want more than one color:

// Gradient Shade colors distribution setting uniform for now
private val positions = null //floatArrayOf(0f, 0.3f, 0.6f)

// Gradient Shade colors
private val colors = intArrayOf(
        ContextCompat.getColor(context,
                R.color.divider_gradient_start_color),
        ContextCompat.getColor(context,
                R.color.divider_gradient_center_color),
        ContextCompat.getColor(context,
                R.color.divider_gradient_end_color))

in OnDraw()

// Add Shader
gradientPaint.shader = LinearGradient(0f, 0f, measuredWidth.toFloat(),0f, 
                colors, 
                positions,
                Shader.TileMode.CLAMP)

canvas.drawPath(path, gradientPaint)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionRohan KView Question on Stackoverflow
Solution 1 - AndroidSujitView Answer on Stackoverflow
Solution 2 - AndroidHitesh SahuView Answer on Stackoverflow