如何使用CoreGraphics绘制椭圆弧?

7
在CoreGraphics中,是否有可能像SVG路径一样绘制椭圆弧?如果可以,具体如何实现?
1个回答

8

今晚我也遇到了同样的问题。CG没有提供一种简单的方法来绘制非圆弧,但是您可以使用CGPath和适当的变换矩阵来完成它。假设您想要一个轴对齐椭圆的弧线,起点在左上角,大小为宽度,高度,则可以按如下方式操作:

CGFloat cx = left + width*0.5;
CGFloat cy = top + height*0.5;
CGFloat r = width*0.5;

CGMutablePathRef path = CGPathCreateMutable();
CGAffineTransform t = CGAffineTransformMakeTranslation(cx, cy);
t = CGAffineTransformConcat(CGAffineTransformMakeScale(1.0, height/width), t);
CGPathAddArc(path, &t, 0, 0, r, startAngle, endAngle, false);
CGContextAddPath(g->cg, path);

CGContextStrokePath(g);

CFRelease(path);

请注意,如果你想绘制一个饼图形状的楔子,只需在 "CGContextAddPath" 调用周围加上 CGContextMoveToPoint(cx,cy) 和 CGContextAddLineToPoint(cx,cy),并且使用 CGContextFillPath 替代 CGContextStrokePath。 (或者如果你想同时填充和描边,请使用 CGContextDrawPath。)

非常好用 - 注意:不要犯我犯过的错误 :). CGAffineTransformMakeTranslation是必须的,即使你正在使用MoveToPoint(因为变换t必须在曲线位于原点时应用,否则苹果的比例变换也会乘以你相对于原点的偏移量!) - Adam
请注意,这也会缩放描边宽度。 - Grodriguez

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接