本屌丝IT男初学IOS,分享一份用UI制作画板的源代码,程序实现了自己选择画笔颜色的功能!主要克服了,修改画笔颜色之后,保留之前的上下文,不做覆盖。
属性:
@property (nonatomic, retain) NSMutableArray*drawedPointArray;
@property (nonatomic, retain) UIButton *button;
@property (nonatomic, retain) NSArray *titleArray;
@property (nonatomic, retain) NSArray *colorArray;
@property (nonatomic, retain) UIColor *color;
@property (nonatomic, retain) NSMutableDictionary *lineDict;
.m文件
staticint k = 0;
- (id)initWithFrame:(CGRect)frame
{
self = [superinitWithFrame:frame];
if (self) {
self.drawedPointArray = [NSMutableArrayarray];
self.lineDict = [NSMutableDictionarydictionary];
self.color = [UIColorredColor];
self.colorArray = @[[UIColorredColor],
[UIColorpurpleColor],
[UIColorblueColor],
[UIColororangeColor],
[UIColorbrownColor],
[UIColorblackColor],
[UIColorgreenColor]];
self.titleArray = @[@"red", @"purple", @"blue", @"orange", @"brown", @"black", @"green"];
}
int x = 0;
int y = 400;
for (inti = 0; i<7; i++) {
self.button = [UIButtonbuttonWithType:UIButtonTypeRoundedRect];
self.button.frame = CGRectMake(16 + 76 * x, y, 60, 40);
[self.buttonsetTitle:[self.titleArrayobjectAtIndex:i]
forState:UIControlStateNormal];
[selfaddSubview:self.button];
self.button.tag = i + 1;
[self.buttonaddTarget:selfaction:@selector(clickButton:) forControlEvents:UIControlEventTouchDown];
x++;
if (i == 3) {
x = 0;
y = 460;
}
}
return self;
}
-(void)clickButton:(UIButton *)butt
{
int index = butt.tag - 1;
self.color = [self.colorArrayobjectAtIndex:index];
}
- (void)drawRect:(CGRect)rect
{
CGContextRef context =UIGraphicsGetCurrentContext();
CGContextSetLineWidth(context, 3);
for (int j = 0; j < [self.drawedPointArraycount]; j++)
{
self.color = [self.lineDictobjectForKey:[NSNumbernumberWithInt:j]];
CGContextSetStrokeColorWithColor(context, self.color.CGColor);
NSArray *array = [self.drawedPointArrayobjectAtIndex:j];
for (inti = 0; i< [array count] - 1; i++)
{
CGPoint pa = [[array objectAtIndex:i] CGPointValue];
CGPointpb = [[array objectAtIndex:i + 1] CGPointValue];
CGContextMoveToPoint(context, pa.x, pa.y);
CGContextAddLineToPoint(context, pb.x, pb.y);
CGContextStrokePath(context);
}
}
}
#pragma -mark touch
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
UITouch *touch =[touches anyObject];
CGPointcurrPoint =[touch locationInView:self];
NSMutableArray *array =[NSMutableArrayarrayWithObject:
[NSValuevalueWithCGPoint:currPoint]];
[self.drawedPointArrayaddObject:array];//记录每一笔的起点
[self.lineDictsetObject:self.colorforKey:[NSNumbernumberWithInt:k]];//记录每一笔的颜色
k++;
}
-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
UITouch *touch = [touches anyObject];
CGPointcurrPoint = [touch locationInView:self];
NSValue *value = [NSValuevalueWithCGPoint:currPoint];
NSMutableArray *array = [self.drawedPointArraylastObject];
[arrayaddObject:value];
[selfsetNeedsDisplay];
}