1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104
| #import "Customview.h"
@implementation Customview { NSMutableArray *lineArray; }
- (id)initWithFrame:(CGRect)frame { self = [super initWithFrame:frame]; if (self) { [self setBackgroundColor:[UIColor whiteColor]]; UIButton *button=[UIButton buttonWithType:UIButtonTypeRoundedRect]; [button setTitle:@"撤销" forState:UIControlStateNormal]; [button addTarget:self action:@selector(doButton:) forControlEvents:UIControlEventTouchDown]; button.frame=CGRectMake(110, 380, 100, 40); [button setBackgroundColor:[UIColor redColor]]; [self addSubview:button]; UIButton *button2=[UIButton buttonWithType:UIButtonTypeRoundedRect]; [button2 setTitle:@"橡皮擦" forState:UIControlStateNormal]; [button2 addTarget:self action:@selector(doButton:) forControlEvents:UIControlEventTouchDown]; button2.frame=CGRectMake(110, 430, 100, 40); [button2 setBackgroundColor:[UIColor redColor]]; [self addSubview:button2];
lineArray =[[NSMutableArray alloc]init]; } return self; }
-(void)doButton:(id)button { [lineArray removeLastObject]; [self setNeedsDisplay]; } -(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event { UITouch *touch = [touches anyObject]; CGPoint firstPoint = [touch locationInView:self]; NSValue *value = [NSValue valueWithCGPoint:firstPoint]; NSMutableArray *pointArray = [[NSMutableArray alloc]init]; [pointArray addObject:value]; [lineArray addObject:pointArray]; } -(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event { UITouch *touch = [touches anyObject]; CGPoint currentPoint = [touch locationInView:self]; NSMutableArray *pointAaary = [lineArray lastObject]; NSValue *value = [NSValue valueWithCGPoint:currentPoint]; [pointAaary addObject:value]; [self setNeedsDisplay];
} -(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event { }
- (void)drawRect:(CGRect)rect { CGContextRef currentText = UIGraphicsGetCurrentContext(); CGContextSetLineWidth(currentText, 2); CGColorRef cf = [UIColor redColor].CGColor; CGContextSetStrokeColorWithColor(currentText, cf); for (int i = 0; i < [lineArray count]; i++) { NSMutableArray *pArray = [lineArray objectAtIndex:i]; for (int j = 0; j < [pArray count]-1; j++) { NSValue *previousValue = [pArray objectAtIndex:j]; NSValue *currentValue = [pArray objectAtIndex:j+1]; CGPoint previousPoint = [previousValue CGPointValue]; CGPoint currentValuePoint = [currentValue CGPointValue]; CGContextMoveToPoint(currentText, previousPoint.x, previousPoint.y); CGContextAddLineToPoint(currentText, currentValuePoint.x, currentValuePoint.y); } CGContextStrokePath(currentText); } } @end
|