Search code examples
androidandroid-canvasandroid-graphics

Creating a circle with 4 segments using canvas in android with rotation


I need to create a segmented circle with four random colours like this:

http://vectips.com/wp-content/uploads/2015/04/39.png. "4segments in a circle"

I have made the following code on referring to android documentation about using canvas.drawArc() but it dosent work as per my expectations as its showing only one segment.

           Bitmap bitMap = Bitmap.createBitmap(100, 100, Bitmap.Config.ARGB_8888);

    bitMap = bitMap.copy(bitMap.getConfig(), true);
    // Construct a canvas with the specified bitmap to draw into
    Canvas canvas = new Canvas(bitMap);
    // Create a new paint with default settings.
    Paint paint = new Paint();
    // smooths out the edges of what is being drawn
    paint.setAntiAlias(true);
    // set color
    paint.setColor(Color.BLUE);

    paint.setStrokeWidth(4.5f);


    RectF oval = new RectF(200F, 200F, 450F, 450F);

    paint.setStyle(Paint.Style.FILL);
    canvas.drawArc(oval, 0F, 90F, true, paint);
    paint.setColor(Color.GREEN);
    canvas.drawArc(oval, 90F, 90F, true, paint);
    paint.setColor(Color.RED);

    canvas.drawArc(oval, 180F, 90F, true, paint);
    paint.setColor(Color.BLACK);

    canvas.drawArc(oval, 270F, 90F, true, paint);

    imageView.setImageBitmap(bitMap);

Solution

  • Your arc angles are wrong. See drawArc Canvas reference, the angle arguments are like this:

    • startAngle - Starting angle (in degrees) where the arc begins

    • sweepAngle - Sweep angle (in degrees) measured clockwise

    Your last arc is covering all the previous ones. You should do something like (Kotlin code below):

    private val oval = RectF(200F, 200F, 450F, 450F)
    
    private val paint = Paint()
    
    override fun onDraw(canvas: Canvas) {
      paint.style = Paint.Style.FILL
    
      paint.color = Color.BLACK
      canvas.drawArc(oval, 0F, 90F, true, paint)
      paint.color = Color.BLUE
      canvas.drawArc(oval, 90F, 90F, true, paint)
      paint.color = Color.RED
      canvas.drawArc(oval, 180F, 90F, true, paint)
      paint.color = Color.GREEN
      canvas.drawArc(oval, 270F, 90F, true, paint)
    }
    

    Will draw something like:

    Sample output

    Java version:

      private RectF oval = new RectF(0F,0F,100F,100F);
    
      private Paint paint = new Paint();
    
      @Override
      protected void onDraw(Canvas canvas) {
        paint.setStyle(Paint.Style.FILL);
    
        paint.setColor(Color.BLACK);
        canvas.drawArc(oval, 0F, 90F, true, paint);
        paint.setColor(Color.BLUE);
        canvas.drawArc(oval, 90F, 1800F, true, paint)
        paint.setColor(Color.RED);
        canvas.drawArc(oval, 0F, 190F, true, paint)
        paint.setColor(Color.GREEN);
        canvas.drawArc(oval, 270F, 360F, true, paint)
      }