简体   繁体   中英

How to draw Smooth straight line by using UIBezierPath?

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM