PruitIgoe
PruitIgoe

Reputation: 6384

Objective-c add a stroke to an arc

I'm following Ray Wenderlich's tutorial on creating an arc and though I don't get any errors I also don't get an arc drawn on the screen. Could someone nudge me in the right direction?

Here's my code:

- (CGMutablePathRef) createArcPathFromBottomOfRect : (CGRect) rect : (CGFloat) arcHeight {

    CGRect arcRect = CGRectMake(rect.origin.x, rect.origin.y + rect.size.height - arcHeight, rect.size.width, arcHeight);

    CGFloat arcRadius = (arcRect.size.height/2) + (pow(arcRect.size.width, 2) / (8*arcRect.size.height));
    CGPoint arcCenter = CGPointMake(arcRect.origin.x + arcRect.size.width/2, arcRect.origin.y + arcRadius);

    CGFloat angle = acos(arcRect.size.width / (2*arcRadius));
    CGFloat startAngle = radians(180) + angle;
    CGFloat endAngle = radians(360) - angle;

    CGMutablePathRef path = CGPathCreateMutable();
    CGPathAddArc(path, NULL, arcCenter.x, arcCenter.y, arcRadius, startAngle, endAngle, 0);
    CGPathAddLineToPoint(path, NULL, CGRectGetMaxX(rect), CGRectGetMinY(rect));
    CGPathAddLineToPoint(path, NULL, CGRectGetMinX(rect), CGRectGetMinY(rect));
    CGPathAddLineToPoint(path, NULL, CGRectGetMinX(rect), CGRectGetMaxY(rect));

    return path;

}

- (void)drawRect:(CGRect)rect {

    CGContextRef currentContext = UIGraphicsGetCurrentContext();

    CGMutablePathRef myArcPath = [self createArcPathFromBottomOfRect:self.frame:10.0];

    CGContextSetLineWidth(currentContext, 1);
    CGFloat red[4] = {1.0f, 0.0f, 0.0f, 1.0f};
    CGContextSetStrokeColor(currentContext, red);
    /*CGContextBeginPath(currentContext);
    CGContextMoveToPoint(currentContext, 0, rect.size.height - 7);
    CGContextAddLineToPoint(currentContext, rect.size.width, rect.size.height - 7);*/
    CGContextAddPath(currentContext, myArcPath);
    CGContextClip(currentContext);
    CGContextStrokePath(currentContext);


}

Upvotes: 0

Views: 377

Answers (1)

Martin R
Martin R

Reputation: 539795

There seem to be two errors: In

CGMutablePathRef myArcPath = [self createArcPathFromBottomOfRect:self.frame:10.0];

you probably should replace self.frame by self.bounds, because the former relates to the coordinates in the superview.

And you probably should remove

CGContextClip(currentContext);

I don't know why you have that, but it modifies the current clip path and then set the current path to an empty path, so that the following CGContextStrokePath() paints nothing.

Upvotes: 1

Related Questions