motionBegan, setStroke and drawRect correct usage - ios

I'm working through a challenge in Big Nerd Ranch's iOS Programming guide in a chapter on UIView subclassing.
I have some code below that draws concentric circles in random colors. And, upon a shake, it should change them all to red. It doesn't because after red is set, drawRect is called again and the random color loop is redone.
Would the correct way to implement this be to move the random color loop somewhere out of drawRect? Do I set a semaphore (messy) to make sure the loop only runs once?
Thanks for your advice.
- (void)setCircleColor:(UIColor *)clr
{
circleColor = clr;
[self setNeedsDisplay];
}
- (BOOL) canBecomeFirstResponder
{
return YES;
}
- (void)motionBegan:(UIEventSubtype)motion withEvent:(UIEvent *)event
{
if (motion == UIEventSubtypeMotionShake) {
[self setCircleColor:[UIColor redColor]];
}
}
-(void)drawRect:(CGRect)dirtyRect
{
CGContextRef ctx = UIGraphicsGetCurrentContext();
CGRect bounds = [self bounds];
// Figure out the center of the bounds rectangle
CGPoint center;
center.x = bounds.origin.x + bounds.size.width / 2.0;
center.y = bounds.origin.y + bounds.size.height / 2.0;
float maxRadius = hypot(bounds.size.width, bounds.size.height) / 2.0;
CGContextSetLineWidth(ctx, 10);
// Set up an array of colors
UIColor *red = [UIColor redColor];
UIColor *green = [UIColor greenColor];
UIColor *yellow = [UIColor yellowColor];
NSArray *colors = [[NSArray alloc]initWithObjects:red, green, yellow, nil];
// Draw concentric circles from the outside in
for (float currentRadius = maxRadius; currentRadius > 0; currentRadius -= 20) {
CGContextAddArc(ctx, center.x, center.y, currentRadius, 0.0, M_PI * 2, YES);
// Random index for colors array
NSUInteger randomIndex = arc4random() % [colors count];
[self setCircleColor:[colors objectAtIndex:randomIndex]];
[[self circleColor] setStroke];
// Perform drawing; remove path
CGContextStrokePath(ctx);
}
NSString *text = #"You are getting sleepy.";
UIFont *font = [UIFont boldSystemFontOfSize:28];
CGRect textRect;
textRect.size = [text sizeWithFont:font];
// Let's put that string in the center of the view
textRect.origin.x = center.x - textRect.size.width / 2.0;
textRect.origin.y = center.y - textRect.size.height / 2.0;
[[UIColor blackColor] setFill];
// Draw a shadow
CGSize offset = CGSizeMake(4, 3);
CGColorRef color = [[UIColor darkGrayColor] CGColor];
CGContextSetShadowWithColor(ctx, offset, 2.0, color);
[text drawInRect:textRect withFont:font];
}
-(id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
[self setBackgroundColor:[UIColor clearColor]];
[self setCircleColor:[UIColor lightGrayColor]];
}
return self;
}
#end

Make a BOOL isSHake and cancel the random colors after you shake the device, the circles will remain red and you can reset that upon another action.

Related

CAShapeLayer Random Fill Color

So I have a pie chart/color wheel that I made using CAShapeLayer and UIBezierPath. The wheel can have a max of 8 sections. I need it so each section is a different color. I've tried setting up an array (colorsArray) with different colors and inserting into the CAShapeLayer's fillColor method but it just takes the last color in the colorsArray. Is there a way to make sure a different color is in each layer section that is created? I'm a little lost right now. Here is my code below. Thanks in advance.
-(void) drawWheel {
CGPoint circleCenter = CGPointMake(self.bounds.size.width / 2, self.bounds.size.height / 2);
//1 Create a view that we’ll put everything else inside.
container = [[UIView alloc] initWithFrame:self.frame];
container.backgroundColor = [UIColor whiteColor];
container.layer.cornerRadius = 100.0;
container.layer.borderColor = [UIColor blackColor].CGColor;
container.layer.borderWidth = 1.0;
CGFloat angleSize = 2*M_PI/numberOfSections;
for (int i = 0; i < numberOfSections; i++) {
CAShapeLayer *slice = [CAShapeLayer layer];
*************************************************
UIColor * color = [UIColor blueColor];
//THIS MAKES THE WHOLE THING One Color - the last color in the colorsArray
for (int i = 0; i < self.colorsArray.count; i++) {
color = [self.colorsArray objectAtIndex:i];
slice.fillColor = (__bridge CGColorRef)(color);
}
*************************************************
slice.strokeColor = [UIColor whiteColor].CGColor;
slice.lineWidth = 3.0;
CGPoint center = CGPointMake(100.0, 100.0);
CGFloat radius = 100.0;
CGFloat startAngle = angleSize * i;
UIBezierPath *piePath = [UIBezierPath bezierPath];
[piePath moveToPoint:center];
[piePath addLineToPoint:circleCenter];
[piePath addArcWithCenter:center radius:radius startAngle:startAngle endAngle:startAngle + angleSize clockwise:YES];
[piePath closePath]; // this will automatically add a straight line to the center
slice.path = piePath.CGPath;
int i = 0;
i++;
[container.layer addSublayer:slice];
}
//7 Adds the container to the main control.
container.userInteractionEnabled = NO;
[self addSubview:container];
//8 Initialize sectors
sectors = [NSMutableArray arrayWithCapacity:numberOfSections];
if (numberOfSections % 2 == 0) {
[self buildSectorsEven];
} else {
[self buildSectorsOdd];
}
}
I figured it out. I took loop that goes through my colorArray. I assigned a variable of "UIColor *color" to the object at the index (i) that matches the number of sections in my for loop "color = [self.colorsArray objectAtIndex:i];" I then assigned the variable color to the slice's fillColor.
Snippet:
for (int i = 0; i < numberOfSections; i++) {
CAShapeLayer *slice = [CAShapeLayer layer];
UIColor *color;
color = [self.colorsArray objectAtIndex:i];
slice.fillColor = [UIColor colorWithCGColor:(__bridge CGColorRef _Nonnull)(color)].CGColor;
Full Code:
-(void) drawWheel {
CGPoint circleCenter = CGPointMake(self.bounds.size.width / 2, self.bounds.size.height / 2);
//1 Create a view that we’ll put everything else inside.
container = [[UIView alloc] initWithFrame:self.frame];
container.backgroundColor = [UIColor whiteColor];
container.layer.cornerRadius = 100.0;
container.layer.borderColor = [UIColor blackColor].CGColor;
container.layer.borderWidth = 1.0;
CGFloat angleSize = 2*M_PI/numberOfSections;
for (int i = 0; i < numberOfSections; i++) {
CAShapeLayer *slice = [CAShapeLayer layer];
UIColor *color;
color = [self.colorsArray objectAtIndex:i];
slice.strokeColor = [UIColor whiteColor].CGColor;
slice.lineWidth = 3.0;
slice.fillColor = [UIColor colorWithCGColor:(__bridge CGColorRef _Nonnull)(color)].CGColor;
CGPoint center = CGPointMake(100.0, 100.0);
CGFloat radius = 100.0;
CGFloat startAngle = angleSize * i;
UIBezierPath *piePath = [UIBezierPath bezierPath];
[piePath moveToPoint:center];
[piePath addLineToPoint:circleCenter];
[piePath addArcWithCenter:center radius:radius startAngle:startAngle endAngle:startAngle + angleSize clockwise:YES];
[piePath closePath]; // this will automatically add a straight line to the center
slice.path = piePath.CGPath;
[container.layer addSublayer:slice];
}
//7 Adds the container to the main control.
container.userInteractionEnabled = NO;
[self addSubview:container];
//8 Initialize sectors
sectors = [NSMutableArray arrayWithCapacity:numberOfSections];
if (numberOfSections % 2 == 0) {
[self buildSectorsEven];
} else {
[self buildSectorsOdd];
}
}

iOS animate parent view's bounds changes child view bounds

I am trying to create a view animation similar to facebook's expanding X when removing a message in the iPhone version. The problem I am facing right now is, I am animating the parent view's bounds using core animation and the resulting subviews animations are animating with it. Ultimately what I want is the parent view to animate and the subview to remain unanimated, in the center of it's parent's view. Below is the code I am using.
#interface FCXView : UIView
#end
#implementation FCXView
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
self.backgroundColor = [UIColor clearColor];
self.layer.opacity = 1.0f;
self.alpha = 1.0f;
self.autoresizingMask = UIViewAutoresizingNone;
}
return self;
}
- (void)drawRect:(CGRect)rect
{
CGContextRef context = UIGraphicsGetCurrentContext();
CGFloat lineWidth2 = 1.0f;
CGContextSetLineWidth(context, lineWidth2);
CGFloat red[4] = {1.0f, 0.0f, 0.0f, 0.9f};
CGContextSetStrokeColor(context, red);
CGContextBeginPath(context);
CGContextMoveToPoint(context, 17.0f, 15.0f);
CGContextAddLineToPoint(context, 28.0f, 30.0f);
CGContextStrokePath(context);
CGContextBeginPath(context);
CGContextMoveToPoint(context, 28.0f, 15.0f);
CGContextAddLineToPoint(context, 17.0f, 30.0f);
CGContextStrokePath(context);
CGContextFillPath(context);
}
#end
#interface FCRoundView ()
#end
#implementation FCRoundView
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
// Initialization code
self.backgroundColor = [UIColor clearColor];
self.layer.opacity = 1.0f;
self.userInteractionEnabled = YES;
self.multipleTouchEnabled = NO;
self.autoresizesSubviews = NO;
[self setupXView];
}
return self;
}
- (void)setupXView
{
// Load X
FCXView *xView = [[FCXView alloc] initWithFrame:CGRectMake(0, 0, 45, 45)];
[self addSubview:xView];
}
- (void)drawRect:(CGRect)rect
{
CGFloat lineWidth = 5;
CGRect borderRect = CGRectInset(rect, lineWidth * 0.5, lineWidth * 0.5);
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetRGBStrokeColor(context, 1.0, 1.0, 1.0, 1.0);
CGContextSetRGBFillColor(context, 175.0/255.0, 175.0/255.0, 175.0/255.0, 0.6);
CGContextSetLineWidth(context, 5.0);
CGContextFillEllipseInRect (context, borderRect);
CGContextStrokeEllipseInRect(context, borderRect);
}
#pragma mark - Handle touch
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
if (self.bounds.size.height == 45) {
SKBounceAnimation *bounceAnimation = [SKBounceAnimation animationWithKeyPath:#"bounds"];
bounceAnimation.fromValue = [NSValue valueWithCGRect:self.frame];
bounceAnimation.toValue = [NSValue valueWithCGRect:CGRectMake(0, 0, 75, 75)];
bounceAnimation.duration = 0.5f;
bounceAnimation.numberOfBounces = 4;
bounceAnimation.delegate = self;
bounceAnimation.removedOnCompletion = NO;
bounceAnimation.fillMode = kCAFillModeForwards;
bounceAnimation.shouldOvershoot = YES;
[self.layer addAnimation:bounceAnimation forKey:#"someKey"];
}
else {
SKBounceAnimation *bounceAnimation = [SKBounceAnimation animationWithKeyPath:#"bounds"];
bounceAnimation.fromValue = [NSValue valueWithCGRect:self.frame];
bounceAnimation.toValue = [NSValue valueWithCGRect:CGRectMake(0, 0, 45, 45)];
bounceAnimation.duration = 0.5f;
bounceAnimation.numberOfBounces = 4;
bounceAnimation.delegate = self;
bounceAnimation.removedOnCompletion = NO;
bounceAnimation.fillMode = kCAFillModeForwards;
[self.layer addAnimation:bounceAnimation forKey:#"someKey1"];
}
}
- (void)animationDidStop:(SKBounceAnimation *)animation finished:(BOOL)flag
{
[self.layer setValue:animation.toValue forKeyPath:animation.keyPath];
[self.layer removeAnimationForKey:#"someKey"];
[self.layer removeAnimationForKey:#"someKey1"];
}

Why isn't this random color method working?

I have a for loop inside the drawRect method that draws a number of circles to fill the screen. I'm trying to make it so each circle has a new random stroke. For some reason nothing is showing up. Here is my randomColor method:
-(UIColor *) randomColor
{
int red, green, blue, alpha;
red = arc4random_uniform(255);
green = arc4random_uniform(255);
blue = arc4random_uniform(255);
alpha = arc4random_uniform(255);
UIColor *colorToReturn = [[UIColor alloc] initWithRed:red green:green blue:blue alpha:alpha];
return colorToReturn;
}
and I try implementing it here:
-(void) drawRect:(CGRect)rect
{
CGContextRef ctx = UIGraphicsGetCurrentContext();
CGRect bounds = [self bounds];
// Firgure out the center of the bounds rectangle
CGPoint center;
center.x = bounds.origin.x + bounds.size.width / 2.0;
center.y = bounds.origin.y + bounds.size.height / 2.0;
// The radius of the circle should be nearly as big as the view
float maxRadius = hypot(bounds.size.width, bounds.size.height) / 2.0;
// The thickness of the line should be 10 points wide
CGContextSetLineWidth(ctx, 10);
// The color of the line should be gray (red/green/blue = 0.6, alpha = 1.0)
// CGContextSetRGBStrokeColor(ctx, 0.6, 0.6, 0.6, 1.0);
// The same as
// [[UIColor colorWithRed:0.6 green:0.6 blue:0.6 alpha:1.0] setStroke];
// The same as
// [[UIColor redColor] setStroke];
// Draw concentric circles from the outside in
for (float currentRadius = maxRadius; currentRadius > 0; currentRadius -= 20) {
// Add a path to the context
CGContextAddArc(ctx, center.x, center.y, currentRadius, 0.0, M_PI * 2.0, YES);
[[self randomColor] setStroke];
// Perform drawing instructions; removes path
CGContextStrokePath(ctx);
}
UIColor takes a float between 0 and 1 as a value for its RGB components:
UIColor *colorToReturn = [[UIColor alloc] initWithRed:red/255.0 green:green/255.0 blue:blue/255.0 alpha:alpha];
I use the two macros below to get a random color. The first one is a straightforward macro that I often use while setting colors. The second one returns a random color using it:
#define _RGB(r,g,b,a) [UIColor colorWithRed:r/255.0 green:g/255.0 blue:b/255.0 alpha:a]
#define kCLR_RANDOM_COLOR _RGB(arc4random()%255, arc4random()%255, arc4random()%255, 1)

RGB Values retrieved from Pixels incorrect

I've rendered a circular gradient and created a method that lets me sweep over it with my finger, using a Pan gesture recognizer.
I am retrieving the pixel at my current touch position and want to retrieve it's color.
This means, the color value should constantly update while moving over the gradient.
i'm using the following code :
- (IBAction)handlePan:(UIPanGestureRecognizer *)sender {
CGPoint translation = [sender translationInView:iv];
[sender setTranslation:CGPointZero inView:self.view];
CGPoint center = sender.view.center;
center.x += translation.x;
center.y += translation.y;
sender.view.center = center;
CGPoint colorPoint = [sender.view.superview convertPoint:center toView:iv];
[sender setTranslation:CGPointMake(0, 0) inView:self.view];
CGImageRef image = img.CGImage;
NSUInteger width = CGImageGetWidth(image);
NSUInteger height = CGImageGetHeight(image);
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
char *rawData = malloc(height * width * 4);
int bytesPerPixel = 4;
int bytesPerRow = bytesPerPixel * width;
NSUInteger bitsPerComponent = 8;
CGContextRef context = CGBitmapContextCreate(
rawData, width, height, bitsPerComponent, bytesPerRow, colorSpace,
kCGImageAlphaPremultipliedLast | kCGBitmapByteOrder32Big
);
CGContextSetBlendMode(context, kCGBlendModeCopy);
CGColorSpaceRelease(colorSpace);
CGContextDrawImage(context, CGRectMake(0, 0, width, height), image);
CGContextRelease(context);
int byteIndex = (bytesPerRow * colorPoint.y) + colorPoint.x * bytesPerPixel;
unsigned char red = rawData[byteIndex];
unsigned char green = rawData[byteIndex+1];
unsigned char blue = rawData[byteIndex+2];
UIColor *hauptfarbe = [UIColor colorWithRed:red green:green blue:blue alpha:1.0];
ch.backgroundColor = hauptfarbe;
NSLog(#"Color value - R : %i G : %i : B %i",red, green, blue);
}
this doesn't work as intended, giving me wrong colors and not showing some colors (like red) at all
EDIT : I cannot add a picture yet due to low rep. i will now add the code for rendering the gradient
Code :
- (void)viewDidLoad
{
[super viewDidLoad];
CGSize size = CGSizeMake(self.view.bounds.size.width, self.view.bounds.size.height);
UIGraphicsBeginImageContextWithOptions(CGSizeMake(size.width, size.height), YES, 0.0);
[[UIColor whiteColor] setFill];
UIRectFill(CGRectMake(0, 0, size.width, size.height));
int sectors = 180;
float radius = MIN(size.width, size.height)/2;
float angle = 2 * M_PI/sectors;
UIBezierPath *bezierPath;
for ( int i = 0; i < sectors; i++)
{
CGPoint center = CGPointMake((size.width/2), (size.height/2));
bezierPath = [UIBezierPath bezierPathWithArcCenter:center radius:radius startAngle:i * angle endAngle:(i + 1) * angle clockwise:YES];
[bezierPath addLineToPoint:center];
[bezierPath closePath];
UIColor *color = [UIColor colorWithHue:((float)i)/sectors saturation:1. brightness:1. alpha:1];
[color setFill];
[color setStroke];
[bezierPath fill];
[bezierPath stroke];
}
img = UIGraphicsGetImageFromCurrentImageContext();
iv = [[UIImageView alloc] initWithImage:img];
[self.view addSubview:iv];
[self.view addSubview:ch];
}
The first problem here is the way you're calculating colorPoint. They way it is now, colorPoint will always be the center point of the view. This handlePan: method should get you the point of the last touch in the view:
- (IBAction)handlePan:(UIPanGestureRecognizer *)sender
{
if (sender.numberOfTouches)
{
CGPoint lastPoint = [sender locationOfTouch: sender.numberOfTouches - 1 inView: sender.view];
NSLog(#"lastPoint: %#", NSStringFromCGPoint(lastPoint));
}
}
From there, I would probably recommend that instead of blitting the image into a bitmap context and then attempting to read back from it at that point, that you just calculate the color for the point using the same mathematical process you used to create the image in the first place. The way you're doing it now is going to be much more CPU + memory intensive.
EDIT: Here's what I came up with. It works for me. Starting from the Single View Application template in Xcode, and using the code you posted, I have the following code in ViewController.m:
#implementation ViewController
{
UIImage* img;
UIImageView* iv;
}
- (void)viewDidLoad
{
[super viewDidLoad];
CGSize size = CGSizeMake(self.view.bounds.size.width, self.view.bounds.size.height);
UIGraphicsBeginImageContextWithOptions(CGSizeMake(size.width, size.height), YES, 0.0);
[[UIColor whiteColor] setFill];
UIRectFill(CGRectMake(0, 0, size.width, size.height));
int sectors = 180;
float radius = MIN(size.width, size.height)/2;
float angle = 2 * M_PI/sectors;
UIBezierPath *bezierPath;
for ( int i = 0; i < sectors; i++)
{
CGPoint center = CGPointMake((size.width/2), (size.height/2));
bezierPath = [UIBezierPath bezierPathWithArcCenter:center radius:radius startAngle:i * angle endAngle:(i + 1) * angle clockwise:YES];
[bezierPath addLineToPoint:center];
[bezierPath closePath];
UIColor *color = [UIColor colorWithHue:((float)i)/sectors saturation:1. brightness:1. alpha:1];
[color setFill];
[color setStroke];
[bezierPath fill];
[bezierPath stroke];
}
img = UIGraphicsGetImageFromCurrentImageContext();
iv = [[UIImageView alloc] initWithImage:img];
[self.view addSubview:iv];
colorView = [[UIView alloc] init];
colorView.frame = CGRectMake(CGRectGetMaxX(bounds) - 25, CGRectGetMaxY(bounds) - 25, 20, 20);
[self.view addSubview:colorView];
UIPanGestureRecognizer *panGesture = [[UIPanGestureRecognizer alloc]
initWithTarget:self action:#selector(handlePan:)];
[self.view addGestureRecognizer: panGesture];
}
- (IBAction)handlePan:(UIPanGestureRecognizer *)sender
{
if (sender.numberOfTouches)
{
CGPoint lastPoint = [sender locationOfTouch: sender.numberOfTouches - 1 inView: sender.view];
CGRect bounds = self.view.bounds;
CGPoint center = CGPointMake(CGRectGetMidX(bounds), CGRectGetMidY(bounds));
CGPoint delta = CGPointMake(lastPoint.x - center.x, lastPoint.y - center.y);
CGFloat angle = (delta.y == 0 ? delta.x >= 0 ? 0 : M_PI : atan2(delta.y, delta.x));
angle = fmod(angle, M_PI * 2.0);
angle += angle >= 0 ? 0 : M_PI * 2.0;
UIColor *color = [UIColor colorWithHue: angle / (M_PI * 2.0) saturation:1. brightness:1. alpha:1];
colorView.backgroundColor = color;
CGFloat r,g,b,a;
if ([color getRed: &r green: &g blue:&b alpha: &a])
{
NSLog(#"Color value - R : %g G : %g : B %g", r, g, b);
}
}
}
#end
What I see is that as I drag my finger over the gradient, I get a steady stream of messages to console with RGB values that correspond to the location of my finger. I've also added code to show the last color in a small view in the lower right. It also doesn't use bitmap contexts. Hope this helps.

Draw line between two moveable circles in objective-c (iPad)

I'm new to objective-c and am trying to draw a line between moveable circles in Objective-c. I already have code that generates circles. Here is an image that I'd like to create in my app.
http://images.sciencedaily.com/2004/04/040407083832.jpg
Here's my code.
CircleViewController.m
- (void)viewDidLoad
{
[super viewDidLoad];
for (int i=0; i<5; i++) {
CGRect circleFrame = CGRectMake(arc4random() % 500, arc4random() % 500, (arc4random() % 200)+50 , (arc4random() % 200)+50);
CircleView *cirleView = [[CircleView alloc] initWithFrame: circleFrame];
cirleView.backgroundColor = [UIColor clearColor];
CGFloat hue = ( arc4random() % 256 / 256.0 ); // 0.0 to 1.0
CGFloat saturation = ( arc4random() % 128 / 256.0 ) + 0.5; // 0.5 to 1.0, away from white
CGFloat brightness = ( arc4random() % 128 / 256.0 ) + 0.5; // 0.5 to 1.0, away from black
UIColor *color = [UIColor colorWithHue:hue saturation:saturation brightness:brightness alpha:1];
cirleView.circleColor = color;
[self.view addSubview:cirleView];
}
}
CircleView.m
-(void) drawCircle:(CGPoint)p withRadius:(CGFloat)radius inContext:(CGContextRef)contex
{
UIGraphicsPushContext(contex);
CGContextBeginPath(contex);
CGContextAddArc(contex, p.x, p.y, radius, 0, 2*M_PI, YES);
CGContextSetLineWidth(contex, 2.0);
CGContextAddLineToPoint(contex, p.x, p.y);
CGContextDrawPath(contex, kCGPathFillStroke);
UIGraphicsPopContext();
}
- (void)drawRect:(CGRect)rect
{
CGFloat size = self.bounds.size.width/2;
if(self.bounds.size.height < self.bounds.size.width) size = self.bounds.size.height / 2;
size *= 0.90;
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetLineWidth(context, 5.0);
[_circleColor setStroke];
[_circleColor setFill];
CGPoint point1;
point1.x = self.bounds.origin.x + self.bounds.size.width/2;
point1.y = self.bounds.origin.y + self.bounds.size.height/2;
[self drawCircle:point1 withRadius:size inContext:context];
UITapGestureRecognizer *singleFingerTap =
[[UITapGestureRecognizer alloc] initWithTarget:self
action:#selector(handleSingleTap:)];
[self addGestureRecognizer:singleFingerTap];
}
Thank you for your help.
Drawing a line:
-(void) drawLine (CGRect circleViewRect1, CGRect circleViewRect2)
{
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetStrokeColorWithColor(context, [UIColor blackColor].CGColor);
//line width
CGContextSetLineWidth(context, 1.0);
CGContextMoveToPoint(context, circleViewRect1.center.x + circleViewRect1.bounds.width/2,circleViewRect1.center.y + circleViewRect1.bounds.height/2); //start from first circle radius
CGContextAddLineToPoint(context, circleViewRect2.center.x + circleViewRect2.bounds.width/2,circleViewRect2.center.y + circleViewRect2.bounds.height/2); //draw to this point
// and now draw the Path!
CGContextStrokePath(context);
}
Note:This is only useful if two circle's centers fall in horizontal line. Also, assume that circleViewRect1 is at the left of circleViewRect2. You must figure out the values for other use cases ie if they are at positioned at different angles etc.

Resources