Search code examples
androidandroid-viewondrawsweepgradient

Drawing a rainbow colored ring in android


I've been trying to draw a rainbow colored ring in android using the following code:

public void init(){
    ringPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
    ringPaint.setStyle(Paint.Style.STROKE);
    ringPaint.setStrokeWidth(8f);
    ringPaint.setShader(new SweepGradient(0, 0, COLORS2, null));
}



@Override
protected void onDraw(Canvas canvas) {
    canvas.drawCircle(getWidth()/2f,getHeight()/2f ,getHeight()/2f - 16f,ringPaint);
}

the value for COLOR2 is the following:

final int[] COLORS2 = new int[]{Color.parseColor("#33004c"), Color.parseColor("#4600d2"),
                                Color.parseColor("#0000ff"), Color.parseColor("#0099ff"),
                                Color.parseColor("#00eeff"),Color.parseColor("#00FF7F"),
                                Color.parseColor("#48FF00"),Color.parseColor("#B6FF00"),
                                Color.parseColor("#FFD700"),Color.parseColor("#ff9500"),
                                Color.parseColor("#FF6200"),Color.parseColor("#FF0000"),
                                Color.parseColor("#33004c")};

The problem is that I'm only getting a subset of the colors, maybe 3 or 4 of the distinct colors in the array and I'm not entirely sure why, can anyone offer some suggestion as to why this is the case?

enter image description here


Solution

  • you should specify center of view instead of 0,0 when create SweepGradient

    look at example please

    public class CustomView extends View {
    
        private Paint ringPaint;
    
        public CustomView(Context context, @Nullable AttributeSet attrs) {
            super(context, attrs);
            init();
        }
    
        public void init() {
            ringPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
            ringPaint.setStyle(Paint.Style.STROKE);
            ringPaint.setStrokeWidth(8f);
        }
    
        @Override
        protected void onSizeChanged(int w, int h, int oldw, int oldh) {
            super.onSizeChanged(w, h, oldw, oldh);
            ringPaint.setShader(new SweepGradient(getWidth() / 2, getHeight() / 2, COLORS2, null));
        }
    
        @Override
        protected void onDraw(Canvas canvas) {
            canvas.drawCircle(getWidth() / 2f, getHeight() / 2f, getHeight() / 2f - 16f, ringPaint);
        }
    }
    

    enter image description here