【问题标题】:How to draw Smooth straight line by using UIBezierPath?如何使用 UIBezierPath 绘制平滑直线?
【发布时间】:2011-11-14 19:39:30
【问题描述】:

我希望能够使用UIBezierPath 在我的 iPad 屏幕上绘制直线。我该怎么办?

我想做的是这样的:我双击屏幕来定义起点。一旦我的手指在屏幕上方,直线就会随着我的手指移动(这应该恰好弄清楚我应该将下一个手指放在哪里,以便它会创建一条直线)。然后,如果我再次双击屏幕,则定义了终点。

此外,如果我双击结束点,应该会开始一个新行。

是否有任何可用资源可供我用作指导?

【问题讨论】:

  • 在投反对票时给出某种解释是常态。
  • @raaz 一旦用户的手指停止接触玻璃,您将无法跟踪它。好吧,除非你用相机实现一些少数派报告式的魔法,但我认为这不值得付出巨大的努力。其余的很容易实现:只需将UITouch 信息汇集到@StuDev 的答案中(UIBezierPath 的要点)。

标签: iphone ipad uibezierpath


【解决方案1】:
UIBezierPath *path = [UIBezierPath bezierPath];
[path moveToPoint:startOfLine];
[path addLineToPoint:endOfLine];
[path stroke];

UIBezierPath Class Reference

编辑

- (void)viewDidLoad
{
    [super viewDidLoad];

    // Create an array to store line points
    self.linePoints = [NSMutableArray array];

    // Create double tap gesture recognizer
    UITapGestureRecognizer *doubleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleDoubleTap:)];
    [doubleTap setNumberOfTapsRequired:2];
    [self.view addGestureRecognizer:doubleTap];
}

- (void)handleDoubleTap:(UITapGestureRecognizer *)sender
{
    if (sender.state == UIGestureRecognizerStateRecognized) {

        CGPoint touchPoint = [sender locationInView:sender.view];

        // If touch is within range of previous start/end points, use that point.
        for (NSValue *pointValue in linePoints) {
            CGPoint linePoint = [pointValue CGPointValue];
            CGFloat distanceFromTouch = sqrtf(powf((touchPoint.x - linePoint.x), 2) + powf((touchPoint.y - linePoint.y), 2));
            if (distanceFromTouch < MAX_TOUCH_DISTANCE) {    // Say, MAX_TOUCH_DISTANCE = 20.0f, for example...
                touchPoint = linePoint;
            }
        }

        // Draw the line:
        // If no start point yet specified...
        if (!currentPath) {
            currentPath = [UIBezierPath bezierPath];
            [currentPath moveToPoint:touchPoint];
        }

        // If start point already specified...
        else { 
            [currentPath addLineToPoint:touchPoint];
            [currentPath stroke];
            currentPath = nil;
        }

        // Hold onto this point
        [linePoints addObject:[NSValue valueWithCGPoint:touchPoint]];
    }
}

我不会在没有金钱补偿的情况下编写任何少数派报告式的相机魔术代码。

【讨论】:

  • @studdev,我已经添加了一些进一步的解释我想要做什么
猜你喜欢
  • 2012-06-09
  • 2016-10-09
  • 2011-07-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-11
相关资源
最近更新 更多