iPad端客户需要做一个实时绘图的功能,因此封装了一个小小的绘图View。
.h
@interface simpleDrawingView : UIView
/// 初始化方法,参数:strokeColor绘图线条颜色,lineWidth绘图线条宽度
- (void)setUpShapeLayerColor:(UIColor *)strokeColor shapeLayerLineWidth:(unsigned int)lineWidth;
@end
.m
#import "simpleDrawingView.h"
@interface simpleDrawingView()
@property (nonatomic, strong) CAShapeLayer * myShapeLayer;
@property (nonatomic, strong) UIBezierPath * myBeizer;
@property (nonatomic, assign) CGPoint startPoint;
@property (nonatomic, assign) CGPoint movePoint;
@end
@implementation simpleDrawingView
- (instancetype)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
UIPanGestureRecognizer *pan = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(panTouch:)];
[self addGestureRecognizer:pan];
self.myBeizer = [UIBezierPath bezierPath];
}
return self;
}
// MARK:初始化方法
- (void)setUpShapeLayerColor:(UIColor *)strokeColor shapeLayerLineWidth:(unsigned int)lineWidth
{
[self.layer addSublayer:self.myShapeLayer];
_myShapeLayer.strokeColor = strokeColor.CGColor;
_myShapeLayer.lineWidth = lineWidth;
}
#pragma mark - getter setter | init 初始化
- (CAShapeLayer *)myShapeLayer
{
if (!_myShapeLayer)
{
_myShapeLayer = [[CAShapeLayer alloc] init];
_myShapeLayer.frame = self.bounds;
_myShapeLayer.fillColor = nil;
_myShapeLayer.lineCap = kCALineCapRound;
}
return _myShapeLayer;
}
#pragma mark - Click Event | 点击事件
-(void)panTouch:(UIPanGestureRecognizer *)sender{
_startPoint = [sender locationInView:self];
if (sender.state == UIGestureRecognizerStateBegan) {
[_myBeizer moveToPoint:_startPoint];
}
if (sender.state == UIGestureRecognizerStateChanged) {
_movePoint = [sender locationInView:self];
[_myBeizer addLineToPoint:_movePoint];
_myShapeLayer.path = _myBeizer.CGPath;
}
}
#pragma mark - Private Method | 私有方法
#pragma mark - 代理方法
@end
只需要在合理处调用,如:
- (void)clickMyButton:(UIButton *)sender
{
simpleDrawingView * mySimpleDrawingView = [[simpleDrawingView alloc]initWithFrame:self.bounds];
[mySimpleDrawingView setUpShapeLayerColor:[UIColor cyanColor] shapeLayerLineWidth:2];
[self addSubview:mySimpleDrawingView];
}
网友评论