gpt4 book ai didi

ios - CGContextAddArc逆时针而不是顺时针

转载 作者:可可西里 更新时间:2023-11-01 03:29:38 26 4
gpt4 key购买 nike

我在 CALayer 子类内的绘图函数内绘制圆弧时遇到问题。该绘图函数的实现如下:

-(void)drawInContext:(CGContextRef)ctx
{
CGPoint center = CGPointMake(self.bounds.size.width/2, self.bounds.size.height/2);
CGFloat radius = MIN(center.x, center.y);

CGContextBeginPath(ctx);

CGContextAddArc(ctx, center.x, center.y, radius, DEG2RAD(0), DEG2RAD(90), YES);

CGContextSetStrokeColorWithColor(ctx, [UIColor whiteColor].CGColor);
CGContextSetLineWidth(ctx, 5);

CGContextDrawPath(ctx, kCGPathStroke);
}

这里并没有太多突破性的东西,但奇怪的是它是逆时针绘制弧线,尽管我指定它应该是顺时针的。相反,当我为 clockwise 参数指定 NO 时,它会顺时针绘制圆弧。我对翻转坐标系进行了一些研究,并认为这可能是这里的问题所在,但我不想只是硬编码与我的意思相反的 bool 参数。有关如何解决此问题的任何建议?

谢谢!

最佳答案

这确实是由于 UIKit 与 Quartz 的坐标系翻转所致。来自docs for CGContext :

The clockwise parameter determines the direction in which the arc is created; the actual direction of the final path is dependent on the current transformation matrix of the graphics context. For example, on iOS, a UIView flips the Y-coordinate by scaling the Y values by -1. In a flipped coordinate system, specifying a clockwise arc results in a counterclockwise arc after the transformation is applied.

您可以通过使用转换矩阵来翻转您的上下文,从而在您的代码中缓解这种情况:

CGContextTranslateCTM(ctx, 0.0, self.bounds.size.height);
CGContextScaleCTM(ctx, 1.0, -1.0);

您可能想在完成绘图后将其翻转回来,即

CGContextSaveGState(ctx);
CGContextTranslateCTM(ctx, 0.0, self.bounds.size.height);
CGContextScaleCTM(ctx, 1.0, -1.0);

// Draw...

CGContextRestoreGState(ctx);

关于ios - CGContextAddArc逆时针而不是顺时针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16974258/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com