如何使用UIBezierPath绘制平滑直线?

时间:2011-11-14 19:39:30

标签: iphone ipad uibezierpath

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

我想做的是这样的:我在屏幕上双击以定义起点。一旦我的手指在屏幕上方,直线就会用我的手指移动(这应该会找出我应该放下我的下一根手指的位置,以便它会形成一条直线)。然后,如果我再次双击屏幕,则定义终点。

此外,如果我双击终点,则应该开始换行。

我是否可以使用任何资源作为指导?

1 个答案:

答案 0 :(得分:8)

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]];
    }
}

我没有写任何少数派报告相机魔术代码而没有金钱补偿。