Track touch points in Multitouch

后端 未结 2 628
不思量自难忘°
不思量自难忘° 2020-12-11 18:11

I am working on a drawing project, I want to support multitouch, I have gone through documentation online, which suggest to track the touch points, I did it , But I am not g

2条回答
  •  一个人的身影
    2020-12-11 19:00

    I always try to use gesture-recognizers when possible. Here I use the UIPanGestureRecognizer:

    - (void)viewDidLoad
    {
        [super viewDidLoad];
        [self.view addGestureRecognizer:[[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(didPan:)]];
    }
    
    - (void)didPan:(UIPanGestureRecognizer*)panGesture {
        for (NSUInteger touchIndex = 0; touchIndex < panGesture.numberOfTouches; touchIndex++) {
            // touchIndex is basically the "source" (the finger) from which the point comes from
            CGPoint p = [panGesture locationOfTouch:touchIndex inView:self.view];
            [self drawAtPoint:p withIndex:touchIndex];
        }
    }
    
    
    - (void)drawAtPoint:(CGPoint)point withIndex:(NSUInteger)index{
        UIView *smallPoint = [[UIView alloc] initWithFrame:CGRectMake(point.x, point.y, 3, 3)];
        [smallPoint setBackgroundColor:[self colorForIndex:index]];
        [self.view addSubview:smallPoint];
    }
    
    - (UIColor*)colorForIndex:(NSUInteger)index {
        switch (index) {
            case 0: return [UIColor redColor];
            case 1: return [UIColor orangeColor];
            case 2: return [UIColor yellowColor];
            case 3: return [UIColor blueColor];
            case 4: return [UIColor greenColor];
        }
        return [UIColor clearColor];
    }
    

    I don't draw a bezier path, but if you drop it in an empty ViewController and run it, you will see that when multi-touching the screen, each finger draws a different colour.

    So if you take into consideration the touchIndex, basically you can keep track of different paths for different fingers.

    Let's say you use two fingers to draw: you will have panGesture.numberOfTouches == 2, and touchIndex 0 will represent the first finger, and touchIndex 1 will represent the second finger. You can accumulate the points in different arrays and add the points to their corresponding path.

提交回复
热议问题