通过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<UITouch *> *)touches withEvent:(UIEvent *)event {
UITouch *touch = [touches anyObject];
/* 设置画笔的宽度*/
self.path.lineWidth = 5.0f;
/* 贝塞尔曲线的初始点 */
[self.path moveToPoint:[touch locationInView:self]];
}
- (void)touchesMoved:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
UITouch *touch = [touches anyObject];
/* 将当前的坐标点添加到贝塞尔曲线中 */
[self.path addLineToPoint:[touch locationInView:self]];
/* 系统自动调用drawRect:方法 */
[self setNeedsDisplay];
}
- (void)touchesEnded:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
UITouch *touch = [touches anyObject];
[self.path addLineToPoint:[touch locationInView:self]];
[self setNeedsDisplay];
}
- (void)touchesCancelled:(NSSet<UITouch *> *)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];
}
本文介绍如何使用UIBezierPath在iOS中实现一个简单的画板功能。通过创建DrawView子类并重写触摸方法,结合UIView和UIBezierPath的API,实现了绘制路径的功能。
5561

被折叠的 条评论
为什么被折叠?



