1

I'm trying draw a custom view which has an Arc which will be filled with gradient of 4 colors and I choose SweepGradient to be suitable for this and when I tried it works fine for two colors and even if add more colors I'm not able to get the other two colors. I tried different combinations of positions as well nothing seem to work.

         int colorRes[] = {R.color.yellow, R.color.green,R.color.oragne, R.color.red};    
         float stops[] = {0,0.3f,0.6f,1};
         int colors[]  = new int[colorRes.length];
            for(int i=0;i<colorRes.length;i++){
                colors[i]= context.getResources().getColor(colorRes[i]);
            }
        Shader gradient = new SweepGradient (wdith/2,height/2, colors, stops));
        lighted.setShader(gradient);
        canvas.drawArc(rectf, 130, 280, false, lightRed);
Kingston
  • 474
  • 5
  • 14

2 Answers2

0

I had similar problem. And the reason why that happened on my side is - the width and the height was 0.

So in reality doing this -

new SweepGradient (wdith/2,height/2, colors, stops));

I got this -

new SweepGradient (0,0, colors, stops));

So to be sure that the width and height wasn't 0 I did it like this -

@Override
    public void onDraw(Canvas canvas) {
        if (mShader == null) {
            float cX = getWidth() / 2F;
            float cY = getHeight() / 2F;
            mShader = new SweepGradient(cX, cY, getRingColors(), null);
        }
        testPaint1.setShader(mShader);
        canvas.drawCircle(getWidth() / 2, getHeight() / 2, getResources().getDimensionPixelSize(R.dimen.status_ring_dimen), testPaint1);
    }



private int[] getRingColors() {
        return new int[]{
                getResources().getColor(R.color.md_blue_500),
                getResources().getColor(R.color.md_red_400),
                getResources().getColor(R.color.md_green_500),
                getResources().getColor(R.color.md_blue_500) 
// the first and last color should be the same to get a smooth transition of colors

        };
    }
Mikelis Kaneps
  • 4,576
  • 2
  • 34
  • 48
0

For me the actual issue was because of a bug in Android Studio which has not been fixed yet.

Please look at the issue reported here

The rendering of SweepGradient in layout preview fails in Android Studio where as in real device it was working fine.

I realized that its always good to test customviews in real devices.

Kingston
  • 474
  • 5
  • 14