How to draw Smooth straight line by using UIBezier

2019-06-07 04:51发布

I want to be able to draw straight lines on my iPad screen using an UIBezierPath. How would I go about this?

What I want to do is something like this: I double tap on the screen to define the start point. Once my finger is above the screen the straight line would move with my finger (this should happen to figure out where I should put my next finger so that it will create a straight line). Then, if I double tap on screen again the end point is defined.

Further, a new line should begin if I double tap on the end point.

Are there any resources available that I can use for guidance?

1条回答
迷人小祖宗
2楼-- · 2019-06-07 05:40
UIBezierPath *path = [UIBezierPath bezierPath];
[path moveToPoint:startOfLine];
[path addLineToPoint:endOfLine];
[path stroke];

UIBezierPath Class Reference

EDIT

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

I'm not writing any Minority Report-esque camera magic code without monetary compensation.

查看更多
登录 后发表回答