iOS绘图弧未按预期工作

时间:2015-01-14 07:47:31

标签: ios quartz-core

我试图用Quartz Core绘制一个简单的弧,但是我没有得到预期的结果。

我的弧线基本为0度到90度弧度(逆时针方向)。

我这里有这个代码:

- (void)drawRect:(CGRect)rect {

    CGContextRef ctx = UIGraphicsGetCurrentContext();

    CGContextSetStrokeColorWithColor(ctx, self.strokeColor.CGColor);

    CGContextMoveToPoint(ctx, self.center.x, self.center.y);

    CGFloat radius = self.bounds.size.width / 2.0;

    CGContextAddArc(ctx, self.center.x, self.center.y, radius, [MathTools degreesToRadians:0], [MathTools degreesToRadians:90], 0);

    CGContextStrokePath(ctx);

}

注意:MathTools只是我为将度数转换为弧度而创建的一个方便的类,反之亦然,degreesToRadians:的实现是:

+(CGFloat)degreesToRadians:(CGFloat)degrees
{
    return degrees * M_PI / 180.0;
}

但我没有在紫色圆圈内看到一个白色圆弧,而是看到的只有白色短划线:

no arc in circle

我试图让它看起来像这样:

expected result

修改

根据rmaddy给出的答案,我的新代码如下:

- (void)drawRect:(CGRect)rect
{
    CGContextRef ctx = UIGraphicsGetCurrentContext();

    CGContextSetStrokeColorWithColor(ctx, self.strokeColor.CGColor);

    CGContextSetLineWidth(ctx, self.strokeWidth);

    CGFloat radius = self.bounds.size.width / 2.0 - self.strokeWidth;

    CGContextAddArc(ctx, CGRectGetMidX(self.bounds), CGRectGetMidY(self.bounds), radius, [MathTools degreesToRadians:0], [MathTools degreesToRadians:-90], 1);

    CGContextStrokePath(ctx);
}

不确定这是否对其他人有所帮助,但根据我在此处看到的情况,似乎Apple的角度正反方向与数学不一样。从内存来看,数学+90度是逆时针方向,但Apple的+90度似乎是顺时针方向。

1 个答案:

答案 0 :(得分:1)

我看到的一个关键问题是您使用self.center。你的意图是移动到视图的中心,但是self.center是相对于视图的框架而不是它的边界。

drawRect:中的所有内容都需要相对于视图的边界而不是其边框。

更改此行:

CGContextMoveToPoint(ctx, self.center.x, self.center.y);

为:

CGContextMoveToPoint(ctx, CGRectGetMidX(self.bounds), CGRectGetMidY(self.bounds));

CGContextAddArc的调用进行类似的更改。

顺便说一句 - self.center唯一适用于此情况的时间是视图的来源是0, 0。对于任何其他来源,self.center将为您提供此案例的问题。