//
// DrawboardView.m
// 画板画图
//
// Created by 品德信息 on 2017/4/17.
// Copyright © 2017年 品德信息. All rights reserved.
//
#import "DrawboardView.h"
@interface DrawboardView ()
//is use eraser 使用橡皮擦
@property (nonatomic, assign) BOOL isEraserEnabled;
//pan color set
@property (nonatomic, strong) UIColor *panColor;
//pan line width
@property (nonatomic, assign) CGFloat panLineWidth;
@property (nonatomic, assign) CGFloat eraserLineWidth;
@property (nonatomic, strong) CAShapeLayer *currentDrawLayer;
@property (nonatomic, strong) UIBezierPath *currentDrawPath;
@property (nonatomic, strong) NSMutableArray *drawLayerArray;
@end
@implementation DrawboardView
//FIXME: MARK --lief cycle ---
- (instancetype)init {
if (self = [super init]) {
self.backgroundColor = [UIColor whiteColor];
self.isEraserEnabled = false;
self.panColor = [UIColor blackColor];
self.panLineWidth = 2.f;
self.eraserLineWidth = 10.f;
}
return self;
}
-(instancetype)initWithFrame:(CGRect)frame{
if (self = [super initWithFrame:frame]) {
self.backgroundColor = [UIColor whiteColor];
self.isEraserEnabled = false;
self.panColor = [UIColor blackColor];
self.panLineWidth = 2.f;
self.eraserLineWidth = 10.f;
}
return self;
}
- (void)dealloc{
[self releaseAllLayers];
}
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
UITouch *touch = touches.anyObject;
CGPoint startPoint = [touch locationInView: self];
self.currentDrawLayer = [self makeDrawLayer:self.isEraserEnabled];
self.currentDrawPath = [self makeDrawPath];
[self.currentDrawPath moveToPoint:startPoint];
}
-(void)touchesMoved:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
UITouch *touch = touches.anyObject;
CGPoint currentPoint = [touch locationInView:self];
[self.currentDrawPath addLineToPoint:currentPoint];
self.currentDrawLayer.path = self.currentDrawPath.CGPath;
}
-(NSMutableArray *)drawLayerArray {
if (!_drawLayerArray) {
_drawLayerArray = [NSMutableArray arrayWithCapacity:10];
}
return _drawLayerArray;
}
#pragma mark -- Custom Methods --
-(CAShapeLayer *)makeDrawLayer:(BOOL)isEraserEnable {
CAShapeLayer *drawLayer = [CAShapeLayer layer];
drawLayer.frame = self.bounds;
drawLayer.fillColor = [UIColor clearColor].CGColor;
//擦除
if (!isEraserEnable) {
drawLayer.lineWidth = self.panLineWidth;
drawLayer.strokeColor = self.panColor.CGColor;
}else{
drawLayer.lineWidth = self.eraserLineWidth;
drawLayer.strokeColor = self.backgroundColor.CGColor;
}
[self.layer insertSublayer:drawLayer atIndex:(unsigned)self.drawLayerArray.count];
[self.drawLayerArray addObject:drawLayer];
return drawLayer;
}
-(UIBezierPath *)makeDrawPath{
UIBezierPath *drawPath = [UIBezierPath bezierPath];
drawPath.lineCapStyle = kCGLineCapRound;
drawPath.lineJoinStyle = kCGLineJoinRound;
return drawPath;
}
- (void)releaseAllLayers {
[self.drawLayerArray makeObjectsPerformSelector:@selector(removeFromSuperlayer)];
[self.drawLayerArray removeAllObjects];
}
@end
网友评论