Objective-C语言画板案例:画线实现
在Objective-C中实现一个简单的画板应用,可以通过捕捉触摸事件来绘制线条。以下是一个基本的实现步骤和示例代码。
首先,我们需要创建一个继承自UIView
的自定义视图类,来处理触摸事件和绘制线条。
步骤:
创建自定义视图类: 新建一个
DrawView
类,继承自UIView
。添加属性:
- 添加一个
NSMutableArray
来存储每根线条的点。 - 添加一个
UIBezierPath
对象来绘制当前的线条。
- 添加一个
实现触摸事件方法:
touchesBegan:withEvent:
: 初始化新的路径,并把起始点添加到该路径。touchesMoved:withEvent:
: 将手指移动时的每个点添加到路径中。touchesEnded:withEvent:
: 完成当前线条的绘制,将路径添加到数组中。
绘制线条:
- 在
drawRect:
方法中遍历存储的线条,使用stroke
方法进行绘制。
- 在
代码实现:
#import "DrawView.h"
@interface DrawView ()
@property (nonatomic, strong) NSMutableArray *lines; // 存储所有线条
@property (nonatomic, strong) UIBezierPath *currentPath; // 当前绘制的线条
@end
@implementation DrawView
- (instancetype)initWithFrame:(CGRect)frame {
self = [super initWithFrame:frame];
if (self) {
_lines = [NSMutableArray array];
self.backgroundColor = [UIColor whiteColor];
}
return self;
}
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
UITouch *touch = [touches anyObject];
CGPoint startPoint = [touch locationInView:self];
self.currentPath = [[UIBezierPath alloc] init];
self.currentPath.lineWidth = 2.0;
[self.currentPath moveToPoint:startPoint];
[self.lines addObject:self.currentPath];
}
- (void)touchesMoved:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
UITouch *touch = [touches anyObject];
CGPoint currentPoint = [touch locationInView:self];
[self.currentPath addLineToPoint:currentPoint];
[self setNeedsDisplay];
}
- (void)drawRect:(CGRect)rect {
[[UIColor blackColor] setStroke];
for (UIBezierPath *path in self.lines) {
[path stroke];
}
}
- (void)clearDrawing {
[self.lines removeAllObjects];
[self setNeedsDisplay];
}
@end
使用该视图:
在你的视图控制器中,创建并添加这个自定义的DrawView
:
#import "ViewController.h"
#import "DrawView.h"
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
DrawView *drawView = [[DrawView alloc] initWithFrame:self.view.bounds];
[self.view addSubview:drawView];
}
@end
解释:
touchesBegan:
: 捕捉触摸开始时,通过UIBezierPath
开始记录绘制路径。touchesMoved:
: 更新路径,记录手指移动的点,调用setNeedsDisplay
来触发视图更新。drawRect:
: 遍历所有的存储线条并绘制。
你可以根据需求扩展这个基本例子,比如添加颜色选择和线宽调整功能,或者实现橡皮擦功能。