Objective-c为弧添加笔划

时间:2013-06-30 11:55:41

标签: objective-c drawrect

我正在关注Ray Wenderlich关于创建弧的教程,虽然我没有得到任何错误,但我也没有在屏幕上绘制弧线。有人能把我推向正确的方向吗?

这是我的代码:

- (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);


}

1 个答案:

答案 0 :(得分:1)

似乎有两个错误:在

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

您可能应该将self.frame替换为self.bounds,因为前者相关 到superview中的坐标。

你可能应该删除

CGContextClip(currentContext);

我不知道为什么会这样,但它会修改当前剪辑路径,然后将当前路径设置为 一条空路径,以便以下CGContextStrokePath()不会描绘任何东西。