分享一个iOS下实现基本绘画板功能的简单方法

2020-01-14 16:46:12王旭

//移动过程中记录这些points  
//调用setNeedsDisplay,会触发drawRect方法的调用  
- (void) touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event  
{  
    CGPoint pt = [[touches anyObject] locationInView:self];  
    [self.points addObject:[NSValue valueWithCGPoint:pt]];  
    [self setNeedsDisplay];  
}  
  
- (void) touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event  
{  
    NSMutableArray *points_tmp = [[NSMutableArray alloc] initWithArray:self.points];  
    if (self.points_all == nil) {  
        self.points_all = [[NSArray alloc] initWithObjects:points_tmp, nil];  
    }else {  
        self.points_all = [self.points_all arrayByAddingObject:points_tmp];  
    }  
}  
@end  

 

ViewController.h

复制代码
#import <UIKit/UIKit.h>  
  
@class TouchView;  
@interface ViewController : UIViewController  
{  
    TouchView *tv;  
}  
@end  

 

ViewController.m

复制代码
#import "ViewController.h"  
#import "TouchView.h"  
  
@interface ViewController ()  
  
@end  
  
@implementation ViewController  
  
- (void)viewDidLoad  
{  
    [super viewDidLoad];  
    // Do any additional setup after loading the view, typically from a nib.  
    self.view.userInteractionEnabled = YES;  
      
  // TouchView *tv = [[TouchView alloc]initWithFrame:CGRectMake(0.0f, 0.0f, 260.0f, 260.0f)];  
    tv = [[TouchView alloc]initWithFrame:self.view.frame];  
    tv.backgroundColor = [UIColor blackColor];  
      
    [self.view addSubview:tv];  
      
    UISegmentedControl *seg = [[UISegmentedControl alloc] initWithItems:[@"White Red Blue Green Yellow" componentsSeparatedByString:@" "]];