【问题标题】:How do I draw a smooth line with a finger slide/touch motion on the iPhone?如何在 iPhone 上通过手指滑动/触摸动作绘制平滑线?
【发布时间】:2011-01-23 03:13:03
【问题描述】:

我有以下代码,但它并不流畅。如果我画一个圆圈,我会看到尖角。

UIGraphicsBeginImageContext(self.view.frame.size);
[drawImage.image drawInRect:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)];
CGContextSetLineCap(UIGraphicsGetCurrentContext(), kCGLineCapRound);
CGContextSetLineWidth(UIGraphicsGetCurrentContext(), 5.0);
CGContextSetAllowsAntialiasing(UIGraphicsGetCurrentContext(), YES);
CGContextSetRGBStrokeColor(UIGraphicsGetCurrentContext(), 1.0, 0.0, 0.0, 1.0);
CGContextBeginPath(UIGraphicsGetCurrentContext());
CGContextMoveToPoint(UIGraphicsGetCurrentContext(), lastPoint.x, lastPoint.y);
CGContextAddLineToPoint(UIGraphicsGetCurrentContext(), currentPoint.x, currentPoint.y);
CGContextStrokePath(UIGraphicsGetCurrentContext());
drawImage.image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

【问题讨论】:

  • 只是一个简短的说明...您可能希望在 UIGraphicsBeginImageContext 之后用一个调用替换您的 UIGraphicsGetCurrentContext 调用,并将结果存储在一个变量中。无需为每一行调用 UIGraphicsGetCurrentContext,效率低且难以阅读。

标签: iphone cocoa ipad draw


【解决方案1】:

您会看到一些尖角,因为您绘制了太多短的抗锯齿线段,所有这些都需要超过 1/60 秒,因此您最终会丢失 UI 触摸事件更新,这会导致更加锯齿小路。

2D CG 绘图在 iOS 设备上没有加速。

如果您想坚持使用 CG 绘图,请尝试仅绘制最后 4 个左右的线段,也许关闭抗锯齿,看看是否更平滑。然后在路径绘制完成后填写其余部分(修饰)。

【讨论】:

    【解决方案2】:

    即使是完整的 60FPS,您也会得到边缘而不是曲线。 CG 的最佳选择是使用贝塞尔路径。在 CG 之外,样条线。

    【讨论】:

      【解决方案3】:

      您需要做的不是每次触摸移动时都调用绘图函数,而是制作一个累加器并在每次调用时递增它。如果它达到某个阈值,那么您将执行绘图代码。但是您绝对应该在第一次调用该方法时运行它。要找到一个好的阈值,您必须对其进行试验。

      static int accum = 0;
      if ((accum == 0) || (accum == threshold)) {
      UIGraphicsBeginImageContext(self.view.frame.size);
      [drawImage.image drawInRect:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)];
      CGContextSetLineCap(UIGraphicsGetCurrentContext(), kCGLineCapRound);
      CGContextSetLineWidth(UIGraphicsGetCurrentContext(), 5.0);
      CGContextSetAllowsAntialiasing(UIGraphicsGetCurrentContext(), YES);
      CGContextSetRGBStrokeColor(UIGraphicsGetCurrentContext(), 1.0, 0.0, 0.0, 1.0);
      CGContextBeginPath(UIGraphicsGetCurrentContext());
      CGContextMoveToPoint(UIGraphicsGetCurrentContext(), lastPoint.x, lastPoint.y);
      CGContextAddLineToPoint(UIGraphicsGetCurrentContext(), currentPoint.x, currentPoint.y);
      CGContextStrokePath(UIGraphicsGetCurrentContext());
      drawImage.image = UIGraphicsGetImageFromCurrentImageContext();
      UIGraphicsEndImageContext();
      accum = 0;
      }
      accum++;
      

      【讨论】:

      • 如果这种方法不够灵敏,您可以根据 currentPoint 和 lastPoint 之间的距离动态更改阈值,阈值应该与差值成反比。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-20
      • 1970-01-01
      • 1970-01-01
      • 2019-05-19
      • 2011-01-16
      • 1970-01-01
      相关资源
      最近更新 更多