iOS_通过UIBezierPath实现简单的画板功能

通过UIBezierPath实现简单的画板功能

说明:
iOS中实现画板功能, 可以有多种方法. 此文使用UIBezierPath(贝塞尔曲线)实现

核心API

Class: UIBezierPath, UIView
Delegate:: 无
API:


/** UIView 类相关*/
- (void)drawRect:(CGRect)rect
- (void)setNeedsDisplay 

/** UIBezierPath 类相关 */
@property(nonatomic) CGFloat lineWidt

- (void)moveToPoint:(CGPoint)point
- (void)addLineToPoint:(CGPoint)point
- (void)stroke

代码

自定义一个UIView子类(DrawView). 重写View中touch相关方法.

DrewView.m文件

#import "DrawView.h"

@interface DrawView ()

@property (nonatomic, strong) UIBezierPath *path; /**< 声明一个曲线属性 */

@end

@implementation DrawView

- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {

        /* 初始化 */
        self.path = [UIBezierPath bezierPath];
    }
    return self;
}



- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {


    UITouch *touch = [touches anyObject];

    /* 设置画笔的宽度*/
    self.path.lineWidth = 5.0f;

    /* 贝塞尔曲线的初始点 */
    [self.path moveToPoint:[touch locationInView:self]];

}


- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {

    UITouch *touch = [touches anyObject];

    /* 将当前的坐标点添加到贝塞尔曲线中 */
    [self.path addLineToPoint:[touch locationInView:self]];

    /* 系统自动调用drawRect:方法 */
    [self setNeedsDisplay];

}


- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {

    UITouch *touch = [touches anyObject];
    [self.path addLineToPoint:[touch locationInView:self]];

    [self setNeedsDisplay];
}


- (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event {
       /* 执行父类方法 */
       [super touchesCancelled:touches withEvent:event];

}


- (void)drawRect:(CGRect)rect {


    /* 画笔的颜色 */
    [[UIColor redColor] setStroke];

    /* 贝塞尔曲线绘画 */
    [self.path stroke];

}

@end

ViewController.m文件

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.

    /* 创建DrawView对象 */
    DrawView *whiteView = [[DrawView alloc] initWithFrame:[UIScreen mainScreen].bounds];

    whiteView.backgroundColor = [UIColor whiteColor];

    [self.view addSubview:whiteView];

}

演示

iOS_通过UIBezierPath实现简单的画板功能_第1张图片

GitHub上的Demo链接

你可能感兴趣的:(iOS)