- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
_lineArray=[NSMutableArray array];//静态方法初始化
[_lineArray retain];//因为是静态方法初始化了 只要出这个函数就会释放 所以retain下
UIButton *undoBtn=[UIButton buttonWithType:UIButtonTypeRoundedRect];//创建个按钮
[undoBtn setTitle:@"undo" forState:UIControlStateNormal];
undoBtn.frame=CGRectMake(320-100, 20, 100, 30);
[undoBtn addTarget:self action:@selector(undoDraw) forControlEvents:UIControlEventTouchUpInside];
[self addSubview:undoBtn];//贴在自己
NSArray *array=[NSArray arrayWithObjects:@"黄色",@"红色",@"蓝色", nil];
// NSArray *a=[NSArray arrayWithObjects:[UIColor yellowColor] ,[UIColor redColor],[UIColor blueColor], nil];
s=[[UISegmentedControl alloc]initWithItems:array];
s.frame=CGRectMake(10, 400, 300, 40);
// s.selectedSegmentIndex=0;
// [s addTarget:self action:@selector(drawRect:) forControlEvents:UIControlEventValueChanged];
// CGContextSetStrokeColorWithColor(c, index:a);//给画笔 添加颜色
[self addSubview:s];
[s release];
}
return self;
}
-(void)undoDraw
{
if ([_lineArray count]==0)
{
return;
}
//[_lineArray removeAllObjects];//全部删除
[_lineArray removeLastObject];//删除最后的数组
[self setNeedsDisplay];//刷新View
}
//重载此方法实现画
- (void)drawRect:(UISegmentedControl *)rect
{
CGContextRef c=UIGraphicsGetCurrentContext();//创建个画布
CGContextSetStrokeColorWithColor(c, [UIColor redColor].CGColor);//给画笔 添加颜色
CGContextSetLineWidth(c, 2.0f);//设置画笔的粗度;
for (NSMutableArray * touchArray in _lineArray)//快速 便利数组
{
if ([touchArray count]==0)
{
continue;
}
for (int i=0; i<[touchArray count]-1; i++)
{
NSValue *v=[touchArray objectAtIndex:i];
CGPoint prePoint=[v CGPointValue];
NSValue *v2=[touchArray objectAtIndex:i+1];
CGPoint currPoint=[v2 CGPointValue];
CGContextMoveToPoint(c, prePoint.x, prePoint.y);//开始坐标
CGContextAddLineToPoint(c, currPoint.x, currPoint.y);//结束坐标
}
}
CGContextStrokePath(c);//开始画,连线
}
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
NSMutableArray *touchArray=[NSMutableArray array];
[_lineArray addObject:touchArray];
}
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
UITouch *t=[touches anyObject];//获取当前的TOUCH
CGPoint currenPoint=[t locationInView:self];//获取当前点击的POINT
NSValue *v=[NSValue valueWithCGPoint:currenPoint];//强转
NSMutableArray *touchArray=[_lineArray lastObject];//在全局变量里面 取出 TOUCHARRAY 局部变量 数组的最后一个
[touchArray addObject:v];
[self setNeedsDisplay];//系统给的 刷新UI 方法
}
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
}
- (void)dealloc {
[_lineArray release];
[super dealloc];
}
Quartz 画笔
最新推荐文章于 2021-05-02 17:35:49 发布