iPhone – Draw a Circle in UIView

Drawing a circle in UIView is similar to drawing a border which is shown in the previous post.
iPhone – UIView with Border

Please follow the above example and modify the UIViewWithBorder.m as below.
UIViewWithBorder.m

...
- (void)drawRect:(CGRect)rect {
  /* Set UIView Border */
  /*
  // Get the contextRef
  CGContextRef contextRef = UIGraphicsGetCurrentContext();
  
  // Set the border width
  CGContextSetLineWidth(contextRef, 5.0);
  
  // Set the border color to RED
  CGContextSetRGBStrokeColor(contextRef, 255.0, 0.0, 0.0, 1.0);
  
  // Draw the border along the view edge
  CGContextStrokeRect(contextRef, rect);
  */
  
  /* Draw a circle */
  // Get the contextRef
  CGContextRef contextRef = UIGraphicsGetCurrentContext();
  
  // Set the border width
  CGContextSetLineWidth(contextRef, 1.0);
  
  // Set the circle fill color to GREEN
  CGContextSetRGBFillColor(contextRef, 0.0, 255.0, 0.0, 1.0);
  
  // Set the cicle border color to BLUE
  CGContextSetRGBStrokeColor(contextRef, 0.0, 0.0, 255.0, 1.0);
  
  // Fill the circle with the fill color
  CGContextFillEllipseInRect(contextRef, rect);
  
  // Draw the circle border
  CGContextStrokeEllipseInRect(contextRef, rect);
}
...

 

Try it out

Done =)

Reference: Draw Circle

9 thoughts on “iPhone – Draw a Circle in UIView”

  1. Thank you for share it, it’s a very nice example for beginners like me… now, can i give to this shape an action (like to a button) ??

    Like

  2. You’d better use CGContextAddArc() with startAngle=0 and endAngle=2*pi if you want a real round circle. My sample code:

        CGContextSetLineWidth(contextRef,2);
        CGContextSetStrokeColorWithColor(contextRef, self.bacv_color) ;
        CGContextAddArc(contextRef,width,width,width-2,0,2*3.1415926535898,1);
        CGContextDrawPath(contextRef,kCGPathStroke);
    

    Like

  3. CGContextSetRGBFillColor(context, 0x00 / 255.0, 0x00 / 255.0, 0xff / 255.0, 0xff / 255.0);
    but not CGContextSetRGBStrokeColor(contextRef, 0.0, 0.0, 255.0, 1.0);

    Like

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.