ios 画板

今天学习了点处理UIView中touch事件的方法 和 图形的绘制,简单写了个绘图板小程序:

主要就是创建一个继承于UIView的类 并重写其中的touch 方法 和drawRect方法


PaintBoard.h

  1. @interface PaintBoard : UIView  
  2. {  
  3.     NSMutableArray *_lineArray; // 存储之前画过的线条  
  4. }  
  5. @end  

PaintBoard.m


  1. @implementation PaintBoard  
  2.   
  3. - (id)initWithFrame:(CGRect)frame  
  4. {  
  5.     self = [super initWithFrame:frame];  
  6.     if (self) {  
  7.         // Initialization code  
  8.         _lineArray = [[NSMutableArray alloc] init];  
  9.     }  
  10.     return self;  
  11. }  
  12.   
  13. - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event  
  14. {  
  15.     UITouch *touch         = [touches anyObject];  
  16.     CGPoint touchPoint     = [touch locationInView:self];  
  17.     NSValue *pointValue    = [NSValue valueWithCGPoint:touchPoint];  
  18.     NSMutableArray *points = [NSMutableArray arrayWithObject:pointValue]; // 当touch开始记录当前画的线条的点  
  19.     [_lineArray addObject:points];   
  20. }  
  21.   
  22. - (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event  
  23. {  
  24.     UITouch *touch         = [touches anyObject];  
  25.     CGPoint touchPoint     = [touch locationInView:self];  
  26.     NSValue *pointValue    = [NSValue valueWithCGPoint:touchPoint];  
  27.     NSMutableArray *points = [_lineArray lastObject];  
  28.     [points addObject:pointValue];  
  29.     [self setNeedsDisplay];  
  30.       
  31. }  
  32.   
  33. // Only override drawRect: if you perform custom drawing.  
  34. // An empty implementation adversely affects performance during animation.  
  35. - (void)drawRect:(CGRect)rect  
  36. {  
  37.     // Drawing code  
  38.       
  39.     CGContextRef context = UIGraphicsGetCurrentContext();  
  40.     CGContextSetStrokeColorWithColor(context, [UIColor redColor].CGColor);  
  41.     CGContextSetLineWidth(context, 2.0f);  
  42.       
  43.     if (_lineArray.count == 0) {  
  44.         return;  
  45.     }  
  46.       
  47.     for (NSArray *lines in _lineArray)  
  48.     {  
  49.         CGPoint startPt = [[lines objectAtIndex:0] CGPointValue];  
  50.         CGContextMoveToPoint(context, startPt.x, startPt.y);  
  51.         for (NSValue *value in lines)  
  52.         {  
  53.             CGPoint endPt = [value CGPointValue];  
  54.             CGContextAddLineToPoint(context, endPt.x, endPt.y);  
  55.         }  
  56.         CGContextStrokePath(context);  
  57.     }  
  58. }  
  59.   
  60.   
  61. @end 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值