今天学习了点处理UIView中touch事件的方法 和 图形的绘制,简单写了个绘图板小程序:
主要就是创建一个继承于UIView的类 并重写其中的touch 方法 和drawRect方法
PaintBoard.h
- @interface PaintBoard : UIView
- {
- NSMutableArray *_lineArray; // 存储之前画过的线条
- }
- @end
PaintBoard.m
- @implementation PaintBoard
- - (id)initWithFrame:(CGRect)frame
- {
- self = [super initWithFrame:frame];
- if (self) {
- // Initialization code
- _lineArray = [[NSMutableArray alloc] init];
- }
- return self;
- }
- - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
- {
- UITouch *touch = [touches anyObject];
- CGPoint touchPoint = [touch locationInView:self];
- NSValue *pointValue = [NSValue valueWithCGPoint:touchPoint];
- NSMutableArray *points = [NSMutableArray arrayWithObject:pointValue]; // 当touch开始记录当前画的线条的点
- [_lineArray addObject:points];
- }
- - (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
- {
- UITouch *touch = [touches anyObject];
- CGPoint touchPoint = [touch locationInView:self];
- NSValue *pointValue = [NSValue valueWithCGPoint:touchPoint];
- NSMutableArray *points = [_lineArray lastObject];
- [points addObject:pointValue];
- [self setNeedsDisplay];
- }
- // 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();
- CGContextSetStrokeColorWithColor(context, [UIColor redColor].CGColor);
- CGContextSetLineWidth(context, 2.0f);
- if (_lineArray.count == 0) {
- return;
- }
- for (NSArray *lines in _lineArray)
- {
- CGPoint startPt = [[lines objectAtIndex:0] CGPointValue];
- CGContextMoveToPoint(context, startPt.x, startPt.y);
- for (NSValue *value in lines)
- {
- CGPoint endPt = [value CGPointValue];
- CGContextAddLineToPoint(context, endPt.x, endPt.y);
- }
- CGContextStrokePath(context);
- }
- }
- @end