UIView可以响应触摸事件,响应有单个手指触摸,也有多点触摸。
判断触摸是几个手指的触摸:
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
NSArray *a = [[event allTouches]allObjects];
NSLog(@"%d",[a count]);
}
写一个程序,像你画我猜中的绘图,把你触摸的路径都画出来,添加一个取消按钮,依次从最后开始删除画的图形。
过程就是有一个数组记住画的所有线条,数组里面的元素也是数组,记住每个线条的点。
只在view头文件中声明一个NSMutable数组,每一个当前触摸点记录在这个数组中的lastObject取得的数组中。
#import "GraphicsView.h"
@implementation GraphicsView
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
// Initialization code
lineArray = [[NSMutableArray alloc]init];
self.backgroundColor = [UIColor whiteColor];
UIButton *cancelBtn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
cancelBtn.frame = CGRectMake(150, 430, 60, 30);
[cancelBtn setTitle:@"cancel" forState:UIControlStateNormal];
[cancelBtn addTarget:self action:@selector(cancelPush:) forControlEvents:UIControlEventTouchUpInside];
[self addSubview:cancelBtn];
}
return self;
}
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect
{
// Drawing code
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetLineWidth(context, 4.0);
CGContextSetStrokeColorWithColor(context, [[UIColor brownColor]CGColor]);
//从线条数组中取出点数组对象
for (int i = 0;i < [lineArray count];i++) {
NSMutableArray *touchArray = [lineArray objectAtIndex:i];
//从点数组中取出每次触摸的点
for (int j = 0;j < [touchArray count];j++ ) {
NSValue *value = [touchArray objectAtIndex:j];
CGPoint p = [value CGPointValue];
//如果是第一个点,把画图远点移到这个点,开始绘图
if (j == 0) {
CGContextMoveToPoint(context, p.x,p.y);
}
else{
CGContextAddLineToPoint(context, p.x, p.y);
}
CGContextAddLineToPoint(context, p.x, p.y);
}
}
CGContextStrokePath(context);
}
//把线数组最后一个对象移除,就是把最后画的那个图形删除,记得调用setNeedsDisplay方法,它自动调用drawRect方法,进行视图更新
-(void)cancelPush:(id)sender{
[lineArray removeLastObject];
[self setNeedsDisplay];
}
//触摸开始
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
NSMutableArray *touchArray = [[NSMutableArray alloc]init];
UITouch *touch = [touches anyObject];
CGPoint p = [touch locationInView:self];
[touchArray addObject:[NSValue valueWithCGPoint:p]];
[lineArray addObject:touchArray];
}
//触摸移动
-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event{
NSMutableArray *touchArray = [lineArray lastObject];
UITouch *touch = [touches anyObject];
CGPoint p = [touch locationInView:self];
[touchArray addObject:[NSValue valueWithCGPoint:p]];
[self setNeedsDisplay];
}
//触摸结束,就是一个线条的结束。
-(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event{
NSMutableArray *touchArray = [lineArray lastObject];
UITouch *touch = [touches anyObject];
CGPoint p = [touch locationInView:self];
[touchArray addObject:[NSValue valueWithCGPoint:p]];
[self setNeedsDisplay];
}
//记得释放内存
-(void)dealloc{
[lineArray release];
[super dealloc];
}
@end