使用CGContext绘制线条

8

我想使用CGContext绘制一条线,目前我的代码如下:

CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetStrokeColorWithColor(context, [UIColor blackColor].CGColor);
CGContextSetLineWidth(context, 1.0f);
CGContextMoveToPoint(context, 10, 10); 
CGContextAddLineToPoint(context, 100, 50);
CGContextStrokePath(context);

它总是从左上角画到右下角。我该如何调整这条线的起始点和终点?我如何调整线的长度?

2个回答

11

CoreGraphics == 好时光。

已经有一段时间没有任何自由绘制的东西了,现在我所做的就是构建所有绘图操作前面的内容。请记住,从Logo时代开始就有一个隐式的“光标”,您可以移动它而不作为绘图操作,但您必须指定它。我认为一个好的方法(至少对于静态图形)是先创建那些需要绘制的路径,然后将路径重复用于像填充、描边和阴影之类的操作。

   CGColorRef fillColor = // yadda
   CGColorRef strokeColor = // yadda

   const CGFloat radius = 5.0;

   // Create the path first - rounded rectangle
   CGMutablePathRef path = CGPathCreateMutable();
   CGPathMoveToPoint(path, NULL, 100.0 - radius, 10.0);
   CGPathAddLineToPoint(path, NULL, 10.0 + radius, 10.0);
   CGPathAddArcToPoint(path, NULL, 10.0, 10.0, 10.0, 10.0 + radius, radius);
   CGPathAddLineToPoint(path, NULL, 10.0, 100.0 - radius);
   CGPathAddArcToPoint(path, NULL, 10.0, 100.0, 10.0 + radius, 100.0, radius);
   CGPathAddLineToPoint(path, NULL, 100.0 - radius, 100.0);
   CGPathAddArcToPoint(path, NULL, 100.0, 100.0, 100.0, 100.0 - radius, radius);
   CGPathAddLineToPoint(path, NULL, 100.0, 10.0 + radius);
   CGPathAddArcToPoint(path, NULL, 100.0, 10.0, 100.0 - radius, 10.0, radius);
   CGPathCloseSubpath(path);

   // Then use it in your draw commands
   CGContextSetStrokeColor(context, CGColorGetComponents(strokeColor));
   CGContextSetFillColor(context, CGColorGetComponents(fillColor));
   CGContextSetLineJoin(context, kCGLineJoinMiter);
   CGContextSetLineWidth(context, strokeWidth);

   CGContextAddPath(context, path);
   CGContextDrawPath(context, kCGPathFillStroke);
   CGPathRelease(path); 

等等,如果你想要,最后可以释放路径,或者保留引用以便以后使用。


1
感谢您发布一些可工作的代码。每次我需要使用CGPathAddArcToPoint时,我都不得不通过试错来弄清楚事情,这并没有带来理解。苹果的文档称这些值为端点,但在图3.5中却谈到了切点。通过在纸上绘制出您的第一个参数(10,10)的作用,我现在看到它本质上是角点,或者用二次贝塞尔曲线的术语来说,它是控制点。将这种理解融入到我正在处理的形状中,将其从倾斜的矩形变成了漂亮的圆角矩形。 - tobinjim
1
你不需要在结尾处加上CGPathRelease(path)吗? - Gene De Lisa

6
这两行代码负责起始点和结束点:
CGContextMoveToPoint(context, 10, 10);    // This sets up the start point
CGContextAddLineToPoint(context, 100, 50); // This moves to the end point.

通过调整这两个 x、y 点,您可以调整线条。线条的长度取决于起点和终点。

在 psoft 的答案之后 - 这是一个基本的示例项目,包括创建路径和描边。

在 Quartz 2D 路径指南中有更详细的解释和更多的示例代码,点击此处


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