How do I detect a touch on a UIBezierPath and move a ball along that?

前端 未结 5 2100
孤城傲影
孤城傲影 2020-12-05 12:20

How do I move a ball along a specific UiBezierPath? Is that possible?

I\'ve tried everything including doing a hit test using

-(BOOL)containsPoint:(         


        
5条回答
  •  生来不讨喜
    2020-12-05 12:30

    there is a method in bezierpath class called containsPoint: .. refer: http://developer.apple.com/library/ios/#documentation/2ddrawing/conceptual/drawingprintingios/BezierPaths/BezierPaths.html

    and you can detect weather the touch point is in bezier path object or not. I have used this with my own method by which a user can easily detect a touch on the bezier path (not inside or out sied if a circle or close path is there).

    This code lets user select a bezier path drawing object on touch of it and a dashed line with animation appears on it. hope it helps someone. Here is code from my own project:

    -(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
    {
    
        if([[self tapTargetForPath:path] containsPoint:startPoint])  // 'path' is bezier path object
              {
    
                    [self selectShape:currentSelectedPath];// now select a new/same shape
    
                    NSLog(@"selectedShapeIndex: %d", selectedShapeIndex);
    
                    break;
                }
    }
    
    // this method will let you easily select a bezier path ( 15 px up and down of a path drawing)
    - (UIBezierPath *)tapTargetForPath:(UIBezierPath *)path
    {
        if (path == nil) {
            return nil;
        }
    
        CGPathRef tapTargetPath = CGPathCreateCopyByStrokingPath(path.CGPath, NULL, fmaxf(35.0f, path.lineWidth), path.lineCapStyle, path.lineJoinStyle, path.miterLimit);
        if (tapTargetPath == NULL) {
            return nil;
        }
    
        UIBezierPath *tapTarget = [UIBezierPath bezierPathWithCGPath:tapTargetPath];
        CGPathRelease(tapTargetPath);
        return tapTarget;
    }
    
    -(void)selectShape:(UIBezierPath *)pathToSelect
    {
        centerline = [CAShapeLayer layer];
        centerline.path = pathToSelect.CGPath;
        centerline.strokeColor = [UIColor whiteColor].CGColor;
        centerline.fillColor = [UIColor clearColor].CGColor;
        centerline.lineWidth = 1.0;
        centerline.lineDashPattern = [NSArray arrayWithObjects:[NSNumber numberWithInt:10], [NSNumber numberWithInt:5], nil];
        [self.layer addSublayer:centerline];
    
        // showing animation on line
        CABasicAnimation *dashAnimation;
        dashAnimation = [CABasicAnimation animationWithKeyPath:@"lineDashPhase"];
    
        [dashAnimation setFromValue:[NSNumber numberWithFloat:0.0f]];
        [dashAnimation setToValue:[NSNumber numberWithFloat:30.0f]];
        [dashAnimation setDuration:1.0f];
        [dashAnimation setRepeatCount:10000];
    
        [centerline addAnimation:dashAnimation forKey:@"linePhase"];
    }
    

提交回复
热议问题