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

About these ads

9 thoughts on “iPhone – Draw a Circle in UIView

  1. olaf

    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) ??

    Reply
  2. Groumfy69

    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);
    
    Reply
  3. dmitry

    CGContextSetRGBFillColor(context, 0×00 / 255.0, 0×00 / 255.0, 0xff / 255.0, 0xff / 255.0);
    but not CGContextSetRGBStrokeColor(contextRef, 0.0, 0.0, 255.0, 1.0);

    Reply
    1. ykyuen Post author

      CGContextSetRGBStrokeColor() is for the border color while the CGContextSetRGBFillColor() is for the color inside the circle.

      Reply

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s