iOS开发——高级篇——iOS涂鸦画板效果实现
生活随笔
收集整理的這篇文章主要介紹了
iOS开发——高级篇——iOS涂鸦画板效果实现
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
一個簡單的繪圖應(yīng)用,模仿蘋果自帶軟件備忘錄里的涂鴉功能
核心代碼
#import "DrawView.h"
#import "DrawPath.h"
@interface DrawView ()
@property (nonatomic, strong) NSMutableArray *paths;
@property (nonatomic, strong) UIBezierPath *path;
@end
@implementation DrawView
- (void)setImage:(UIImage *)image
{
_image = image;
[self.paths addObject:image];
[self setNeedsDisplay];
}
// 撤銷
- (void)undo
{
[self.paths removeLastObject];
[self setNeedsDisplay];
}
- (void)clear
{
// 清除畫板view所有的路徑,并且重繪
[self.paths removeAllObjects];
[self setNeedsDisplay];
}
- (void)awakeFromNib
{
_lineWidth = 1;
_lineColor = [UIColor blackColor];
}
- (NSMutableArray *)paths
{
if (_paths == nil) {
_paths = [NSMutableArray array];
}
return _paths;
}
// 當(dāng)手指點(diǎn)擊view,就需要記錄下起始點(diǎn)
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
// 獲取UITouch
UITouch *touch = [touches anyObject];
// 獲取起始點(diǎn)
CGPoint curP = [touch locationInView:self];
// 只要一開始觸摸控件,設(shè)置起始點(diǎn)
DrawPath *path = [DrawPath path];
path.lineColor = _lineColor;
[path moveToPoint:curP];
path.lineWidth = _lineWidth;
// 記錄當(dāng)前正在描述的路徑
_path = path;
// 保存當(dāng)前的路徑
[self.paths addObject:path];
}
// 每次手指移動的時候調(diào)用
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
// 獲取UITouch
UITouch *touch = [touches anyObject];
// 獲取當(dāng)前觸摸點(diǎn)
CGPoint curP = [touch locationInView:self];
[_path addLineToPoint:curP];
// 重繪
[self setNeedsDisplay];
}
// 繪制東西
- (void)drawRect:(CGRect)rect
{
for (DrawPath *path in self.paths) {
if ([path isKindOfClass:[UIImage class]]) { // 圖片
UIImage *image = (UIImage *)path;
[image drawAtPoint:CGPointZero];
}else{
[path.lineColor set];
[path stroke];
}
}
}
@end
用法很簡單,導(dǎo)入DrawView.h DrawView.m 文件創(chuàng)建該控件即可
清屏: [_drawView clear];
撤銷: [_drawView undo];
橡皮擦: _drawView.lineColor = [UIColor whiteColor];
github地址:https://github.com/chglog/scrawl
總結(jié)
以上是生活随笔為你收集整理的iOS开发——高级篇——iOS涂鸦画板效果实现的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: java向飞秋发文件_Java 给飞秋发
- 下一篇: fat32 linux 打包工具_11款