61

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..

Vadim Kotov
  • 8,084
  • 8
  • 48
  • 62
Rohan K
  • 1,608
  • 4
  • 21
  • 32

2 Answers2

129

use the code below..

paint.setShader(new LinearGradient(0, 0, 0, getHeight(), Color.BLACK, Color.WHITE, Shader.TileMode.MIRROR));
    canvas.drawPath(arrowPath, paint);
Sujit
  • 10,512
  • 9
  • 40
  • 45
14

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)
Vadim Kotov
  • 8,084
  • 8
  • 48
  • 62
Hitesh Sahu
  • 41,955
  • 17
  • 205
  • 154