UIBezierPath пересекаются

искал ответ в течение нескольких часов, но не нашел ничего по теме.

У меня есть вопрос, связанный с Objective-c. Я'создаю приложение, в котором UIView проверяет наличие прикосновений от пользователя, и если пользователь касается и перемещает свой палец, рисуется путь с использованием UIBezierPath. Если пользователь рисует так, что путь пересекает себя, он должен исчезнуть с экрана. Когда пользователь завершит рисование шаблона, линия от последней точки на пути должна автоматически соединиться с первой точкой на пути (I 'м по методуclosePath» для этого), если эта линия пересекается с другойлиния" в пути путь также должен исчезнуть с экрана.

Я сохраняю каждую точку прикосновения в CGPoint, которую храню в другом классе, называемом Line, как точка A и точка B. I 'м тогда сохраняюлиния" к NSMutableArray под названием "линии», Каждый раз, когда к пути добавляется точка, я проверяю, пересекается ли линия между этой точкой и точкой, нарисованной до того, каклинии» в строках с помощью метода (- (BOOL) checkLineIntersection: (CGPoint) p1: (CGPoint) p2: (CGPoint) p3: (CGPoint) p4) Я получил из этого урока "http://www.iossourcecode.com/2012/08/02/how-to-make-a-game-like-cut-the-rope-part-2/».

Эта проблема

Проблема в том, что когда я запускаю приложение, оно иногда работает, но иногда, когда я рисую так, чтобы линии пересекались, путь нет исчезнуть. Я могу'Я не понимаю, почему ... Кажется, это происходит чаще, когда я рисую медленно.

Код:

MyView.h:

#import 
#import "Line.h"
@interface MyView : UIView {

NSMutableArray *pathArray;
UIBezierPath *myPath;
NSMutableArray *lines;
Line *line;
} 

@end

MyView.m:

#import "MyView.h"

@implementation MyView


- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
    // Initialization code
    pathArray=[[NSMutableArray alloc]init];

}
return self;
}

- (void)drawRect:(CGRect)rect
{
[[UIColor redColor] setStroke];
[[UIColor blueColor] setFill];

for (UIBezierPath *_path in pathArray) {
    //[_path fill];

    [_path strokeWithBlendMode:kCGBlendModeNormal alpha:1.0];
}
}

#pragma mark - Touch Methods
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
myPath = [[UIBezierPath alloc]init];
lines = [[NSMutableArray alloc]init];
myPath.lineWidth=1;

UITouch *mytouch = [[event allTouches] anyObject];
[myPath moveToPoint:[mytouch locationInView:mytouch.view]];

[pathArray addObject:myPath];

}

-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{

if(myPath.isEmpty) {

} else {

    UITouch *mytouch = [[event allTouches] anyObject];
    [myPath addLineToPoint:[mytouch locationInView:mytouch.view]];

    CGPoint pointA = [mytouch previousLocationInView:mytouch.view];
    CGPoint pointB = [mytouch locationInView:mytouch.view];

    line = [[Line alloc]init];
    [line setPointA:pointA];
    [line setPointB:pointB];

    [lines addObject:line];

    for(Line *l in lines) {

        CGPoint pa = l.pointA;
        CGPoint pb = l.pointB;

        //NSLog(@"Point A: %@", NSStringFromCGPoint(pa));
        //NSLog(@"Point B: %@", NSStringFromCGPoint(pb));

        if ([self checkLineIntersection:pointA :pointB :pa :pb])
        {
            [pathArray removeLastObject];
            [myPath removeAllPoints];
            [self setNeedsDisplay];
            NSLog(@"Removed path!");
            return;
        }
    }
}
[self setNeedsDisplay];
}

-(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
if(myPath.isEmpty) {


} else if ([lines count] != 0){
    line = [[Line alloc]init];
    line = [lines lastObject];
    CGPoint pointA = line.pointA;
    line = [[Line alloc]init];
    line = [lines objectAtIndex:0];
    CGPoint pointB = line.pointA;

    [myPath closePath];
    for(Line *l in lines) {

        CGPoint pa = l.pointA;
        CGPoint pb = l.pointB;

        if ([self checkLineIntersection:pointA :pointB :pa :pb])
        {
            [pathArray removeLastObject];
            [myPath removeAllPoints];
            [self setNeedsDisplay];
            NSLog(@"Removed path!");
            return;
        }
    } 
}
[self setNeedsDisplay];
}

-(BOOL)checkLineIntersection:(CGPoint)p1 :(CGPoint)p2 :(CGPoint)p3 :(CGPoint)p4
{
CGFloat denominator = (p4.y - p3.y) * (p2.x - p1.x) - (p4.x - p3.x) * (p2.y - p1.y);

/*
// In this case the lines are parallel so you assume they don't intersect
if (denominator == 0.0f)
    return NO;
*/

CGFloat ua = ((p4.x - p3.x) * (p1.y - p3.y) - (p4.y - p3.y) * (p1.x - p3.x)) / denominator;
CGFloat ub = ((p2.x - p1.x) * (p1.y - p3.y) - (p2.y - p1.y) * (p1.x - p3.x)) / denominator;

if (ua > 0.0 && ua < 1.0 && ub > 0.0 && ub < 1.0)
{
    return YES;
}

return NO;
}


@end

Line.h:

#import 

@interface Line : UIView 

@property (nonatomic, assign) CGPoint pointA;
@property (nonatomic, assign) CGPoint pointB;

@end

Line.m:

#import "Line.h"

@implementation Line

@synthesize pointA;
@synthesize pointB;

- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
    // Initialization code
}
return self;
}

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect
{
// Drawing code
}
*/

@end

Я надеюсь, что кто-то сможет ответить на это. Извините еслиЧто-то очевидное. Заранее спасибо!

Ответы на вопрос(2)

Ваш ответ на вопрос