您的位置:首页 > 其它

涂鸦-每次调setNeedsDisplay以后就会重新调用一次drawRect方法,每次调drawRect方法就会把之前画好的东西删掉

2014-09-11 19:41 330 查看
//
// WJView.m
// zwj涂鸦
//
// Created by zwj on 14-9-9.
// Copyright (c) 2014年 zwj. All rights reserved.
//

#import "WJView.h"

@interface WJView()
@property(nonatomic,strong) NSMutableArray *allPaths;
@end

@implementation WJView

- (void)backto{
[self.allPaths removeLastObject];
[self setNeedsDisplay];
}
- (void)clearScreen{
[self.allPaths removeAllObjects];
[self setNeedsDisplay];
}

-(NSMutableArray *)allPaths{
if (_allPaths == nil) {
_allPaths = [NSMutableArray array];
}
return _allPaths;
}

- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
// Initialization code
}
return self;
}

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
UITouch *touch = [touches anyObject];
CGPoint currentPoint = [touch locationInView:touch.view];
NSMutableArray *aryCurrentP = [NSMutableArray array];
[aryCurrentP addObject:[NSValue valueWithCGPoint:currentPoint]];
[self.allPaths addObject:aryCurrentP];
[self setNeedsDisplay];
}

-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event{
UITouch *touch = [touches anyObject];
CGPoint currentP = [touch locationInView:touch.view];
NSMutableArray *ary = [self.allPaths lastObject];
[ary addObject:[NSValue valueWithCGPoint:currentP]];
[self setNeedsDisplay];
}

-(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event{
UITouch *touch = [touches anyObject];
CGPoint currentP = [touch locationInView:touch.view];
NSMutableArray *ary = [self.allPaths lastObject];
[ary addObject:[NSValue valueWithCGPoint:currentP]];
[self setNeedsDisplay];
}

/**
* 绘制图形
*/
-(void)drawRect:(CGRect)rect{
CGContextRef ref = UIGraphicsGetCurrentContext();
for (NSMutableArray *ary in self.allPaths) {
for (int i = 0; i < ary.count; i++) {
if (i == 0) {
CGPoint firstPoint = [ary[i] CGPointValue];
CGContextMoveToPoint(ref, firstPoint.x, firstPoint.y);
} else {
CGPoint movePoint = [ary[i] CGPointValue];
CGContextAddLineToPoint(ref, movePoint.x, movePoint.y);
}
}
}
CGContextSetLineJoin(ref, kCGLineJoinRound);
CGContextSetLineWidth(ref, 5);
CGContextStrokePath(ref);
}

@end
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: