多点触控及一个华丽的Demo

来源:互联网 发布:淘宝上买警官证 编辑:程序博客网 时间:2024/05/16 06:18

 

1.触摸过程

一次完整的触摸过程,会经历3个状态:

触摸开始:

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event

触摸移动:

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

触摸结束:

-(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event

触摸取消(可能会经历):

-(void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event

 

2.触摸过程的理解

 

a.4个触摸事件处理方法中,都有NSSet *touches和UIEvent *event两个参数。一次完整的触摸过程中,只会产生一个事件对象,4个触摸方法都是同一个event参数;

 

b.如果两根手指同时触摸一个view,那么view只会调用一次touchesBegan:withEvent:方法,这时touches参数中装着2个UITouch对象;

 

c.如果这两根手指一前一后分开触摸同一个view,那么view会分别调用2次touchesBegan:withEvent:方法,并且每次调用时的touches参数中只包含一个UITouch对象;

 

d.根据touches中UITouch的个数可以判断出是单点触摸还是多点触摸;

 

e.注意: 一般默认情况下, 控件都不支持多点触摸(为了提高性能), 所以需要手动设置一个UIView 允许多点触摸!

 

3. 多点触控的一个华丽Demo

 

@interfaceCZView ()

//定义一个数组存放image图片

@property(nonatomic, strong) NSArray* images;

@end

 

@implementationCZView

//懒加载

-(NSArray*)images

{

if(!_images) {

    _images = @[ [UIImageimageNamed:@"spark_green"], [UIImageimageNamed:@"spark_red"] ];

}

return_images;

}

//手指按下屏幕

-(void)touchesBegan:(NSSet*)touches withEvent:(UIEvent*)event

{

 [self addSpark:touches];

}

//手指在屏幕上移动

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

{

 [self addSpark:touches];

}

-(void)addSpark:(NSSet*)touches

{

inti = 0;

//获取触摸对象

for(UITouch* t in touches) {

    // 获取手指的位置

    CGPoint p = [t locationInView:t.view];

    // 创建一个imageView

    UIImageView* imageView = [[UIImageViewalloc] initWithImage:self.images[i]];

 

    // 让imageView的center等于手指的位置

    imageView.center = p;

    // 添加到控制器的view上

    [selfaddSubview:imageView];

    [UIView animateWithDuration:2

        animations:^{

            imageView.alpha = 0;

        }

        completion:^(BOOL finished) {

            [imageView removeFromSuperview];

        }];

 

    i++;

}

}

@end

输出结果:

 

 


0 0
原创粉丝点击