45

Given a closed Path object result is like this:

enter image description here

Although that is a rectangle I'm looking for something which works with any closed Path.

Girish Nair
  • 5,148
  • 5
  • 40
  • 61
Carl Whalley
  • 3,011
  • 8
  • 33
  • 48

2 Answers2

81

While steelbytes' answer will probably give you more control over the individual sections of the gradient, you can do it without the path:

Paint m_Paint = new Paint();
protected void onDraw(Canvas canvas)
{
    super.onDraw(canvas);
    // start at 0,0 and go to 0,max to use a vertical
    // gradient the full height of the screen.
    m_Paint.setShader(new LinearGradient(0, 0, 0, getHeight(), Color.BLACK, Color.WHITE, Shader.TileMode.MIRROR));
    canvas.drawPaint(m_Paint);
}
idbrii
  • 10,975
  • 5
  • 66
  • 107
  • 46
    ok but NEVER construct the Paint instance in the onDraw(...) methods – ebtokyo Jun 23 '13 at 07:34
  • @ebtokyo: For performance reasons? Would you cache it on creation and and update its size on each onDraw (or maybe in resize)? – idbrii Jul 02 '13 at 22:06
  • Yes, for performance reasons. Lint comments allocations in onDraw() like this: "Avoid object allocations during draw/layout operations (preallocate and reuse instead)" – Herr von Wurst Sep 23 '13 at 04:22
  • 2
    @ebtokyo: also LinearGradient instance should be pr-instansiated in another stage on the view lifycle – Tal Kanel May 14 '14 at 05:11
  • @TalKanel You cannot modify `LinearGradient`, so you have to reinstantiate it. Maybe not in `onDraw`, but in `onLayout` or in `onMeasure`. But you will get a lint warning anyhow. – Aleks N. Jun 20 '19 at 13:32
32

this may help.

Note: it's not efficient to create the Paint etc in every call to onDraw. This is just an demonstration of LinearGradient shader

protected void onDraw(Canvas canvas)
{
    super.onDraw(canvas);
    int w = getWidth();
    int h = getHeight();
    Paint p = new Paint(Paint.ANTI_ALIAS_FLAG|Paint.FILTER_BITMAP_FLAG);
    Path pth = new Path();
    pth.moveTo(w*0.27f,0);
    pth.lineTo(w*0.73f,0);
    pth.lineTo(w*0.92f,h);
    pth.lineTo(w*0.08f,h);
    pth.lineTo(w*0.27f,0);
    p.setColor(0xff800000);
    p.setShader(new LinearGradient(0,0,0,h,0xff000000,0xffffffff,Shader.TileMode.CLAMP));
    canvas.drawPath(pth,p);
}   
SteelBytes
  • 6,905
  • 1
  • 26
  • 28