objective-c用CG创建和绘制一个弧



我遵循Ray Wenderlich关于创建弧线的教程:

http://www.raywenderlich.com/33193/core-graphics-tutorial-arcs-and-paths

——我想做的是从点a(一个固定点)开始,定位用户触摸屏幕的位置,如果它是+点a,那么我想画一个到该点的弧。虽然我没有返回任何错误,但我也没有得到要描边的路径。有人可以审查下面的代码,看看我做错了什么?

    @implementation KIP_Arc
- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code
    }
    return self;
}
- (void) setArc {
    //set the frame
    float frameX = _startPoint.x;
    float frameY = _startPoint.y;
    float frameW = _endPoint.x;
    float frameH = 50.0;
    [self setFrame:CGRectMake(frameX, frameY, frameW, frameH)];
    self.backgroundColor = [UIColor clearColor];
}
- (BOOL)isFlipped {
    return YES;
}

- (void)drawRect:(CGRect)rect  {
    [[UIColor blackColor] set];
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSaveGState(context);
    CGRect arcRect = self.frame;
    CGMutablePathRef arcPath = [self createArcPathFromBottomOfRect:arcRect:25.0];
    CGContextAddPath(context, arcPath);
    CGContextClip(context);
    CGContextFillPath(context);
    CGContextRestoreGState(context);
    CFRelease(arcPath);
}
- (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;
}
static inline double radians (double degrees){
    return degrees * M_PI/180;
}

CGContextClip作为副作用,清空当前路径。当您随后立即调用CGContextFillPath时,当前路径为空,因此您不填充任何内容。

顾名思义,CGContextFillPath将自己限制为上下文的当前路径。(如果没有,它的名字就会是CGContextFill。)所以,你不需要剪辑。

放弃CGContextClip调用,只使用CGContextFillPath

相关内容

最新更新