.h
#import "HanBaseView.h"
NS_ASSUME_NONNULL_BEGIN
@interface HanHandWritingView : HanBaseView
//撤销
-(void)returnBack;
///清空
-(void)clear;
///截屏
- (UIImage*)screenSnapshot;
@end
NS_ASSUME_NONNULL_END
.m
#import "HanHandWritingView.h"
@interface HanHandWritingView()
@property(nonatomic,strong)NSMutableArray *beginArr;
@property (nonatomic,strong) NSMutableArray<UIBezierPath *> *pathArr;
@end
@implementation HanHandWritingView{
CGPoint beginPoint;
CGPoint endPoint;
}
-(instancetype)initWithFrame:(CGRect)frame{
self = [super initWithFrame:frame];
if (self) {
[self setBackgroundColor:[UIColor whiteColor]];
}
return self;
}
-(void)drawRect:(CGRect)rect{
[[UIColor blackColor] setStroke];
for (int i = 0; i < self.pathArr.count; i++) {
UIBezierPath *path = self.pathArr[i];
[path stroke];
}
}
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
beginPoint = [[touches anyObject] locationInView:self];
UIBezierPath *path = [UIBezierPath bezierPath];
[path setLineWidth:3];
[path moveToPoint:beginPoint];
[self.pathArr addObject:path];
}
-(void)touchesMoved:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
CGPoint point = [[touches anyObject] locationInView:self];
UIBezierPath *path = self.pathArr.lastObject;
[path addLineToPoint:point];
[self setNeedsDisplayInRect:self.bounds];
}
-(void)touchesEnded:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
// [self.array removeAllObjects];
}
#pragma mark - 公共方法
///清空
-(void)clear{
[self.pathArr removeAllObjects];
[self setNeedsDisplayInRect:self.bounds];
}
//撤销
-(void)returnBack{
[self.pathArr removeLastObject];
[self setNeedsDisplayInRect:self.bounds];
}
///截屏
- (UIImage*)screenSnapshot{
UIGraphicsBeginImageContextWithOptions(self.frame.size, NO, 0);
[self.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage * image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
UIImage * iii = [[UIImage alloc] initWithData: UIImageJPEGRepresentation(image, 0.8)];
return iii;
}
#pragma mark - getter
-(NSMutableArray *)pathArr{
if (!_pathArr) {
_pathArr = [[NSMutableArray alloc] init];
}
return _pathArr;
}
-(NSMutableArray *)beginArr{
if (!_beginArr) {
_beginArr = [NSMutableArray array];
}
return _beginArr;
}
@end
网友评论