【问题标题】:Using CGContext to draw line使用CGContext画线
【发布时间】:2012-02-23 01:09:12
【问题描述】:

我想用 CGContext 画一条线,目前我得到的是:

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

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

【问题讨论】:

    标签: iphone objective-c ios ipad cgcontext


    【解决方案1】:

    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); 
    

    等等。如果需要,您可以在最后释放路径,或者保留参考以供以后使用。

    【讨论】:

    • 感谢您发布一些工作代码。每次我需要 CGPathAddArcToPoint 时,我都必须通过尝试错误来解决问题,这并没有导致理解。 Apple 的文档将值称为端点,但随后在图 3.5 中谈到了切点。通过在纸上画出你的第一个参数 (10,10) 正在做什么,我现在看到它本质上是角点,或者就二次贝塞尔曲线而言,它是控制点。将这种理解转化为我正在处理的形状,将它从一个倾斜的矩形变成了一个漂亮的圆角矩形。
    • 你不需要 CGPathRelease(path);最后?
    【解决方案2】:

    这两行分别负责起点和终点:

    CGContextMoveToPoint(context, 10, 10);    // This sets up the start point
    CGContextAddLineToPoint(context, 100, 50); // This moves to the end point.
    

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

    从 psoft 的回答开始 - 这是一个基本的 example project 绘图,包括创建路径和抚摸它。

    paths 的 Quartz 2D 指南中的更多示例代码对此进行了更详细的解释。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-04-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-04-18
      • 1970-01-01
      相关资源
      最近更新 更多