生活随笔
收集整理的這篇文章主要介紹了
iOS开发核心动画之画图板
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
1. 效果圖
2. 用一個View來描述畫圖板,給畫圖板添加拖動的手勢
// 從xib中加載- (void)awakeFromNib{ [self setUpGesture];}// 代碼創(chuàng)建- (instancetype)initWithFrame:(CGRect)frame{ if (self = [super initWithFrame:frame]) { [self setUpGesture]; } return self;}// 初始化添加拖動手勢- (void)setUpGesture{ UIPanGestureRecognizer *pan = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(pan:)]; [self addGestureRecognizer:pan]; self.color = [UIColor blackColor]; self.width = 1;}3. 監(jiān)聽手勢方法
1> 判斷拖動開始拖動設(shè)置為路徑的的起始點(diǎn),添加路徑并保存路徑,將當(dāng)前路徑添加到數(shù)組中
設(shè)置路徑的相關(guān)屬性(顏色/寬度/圓角)
2> 拖動過程中的點(diǎn)添加直線重繪
// 監(jiān)聽手勢方法- (void)pan:(UIPanGestureRecognizer *)pan{ // 獲取當(dāng)前觸摸點(diǎn) CGPoint curP = [pan locationInView:self]; if (pan.state == UIGestureRecognizerStateBegan) { // 開始拖動 // 獲取開始點(diǎn) CGPoint startP = curP; // 創(chuàng)建路徑 LDBezierPath *path = [[LDBezierPath alloc] init]; self.path = path; [self.pathArray addObject:path]; // 設(shè)置寬度 [path setLineWidth:self.width]; // 設(shè)置顏色 [path setLineColor:self.color]; // 設(shè)置圓角 [path setLineJoinStyle:kCGLineJoinRound]; [path setLineCapStyle:kCGLineCapRound]; // 添加起始點(diǎn) [path moveToPoint:startP]; } else if (pan.state == UIGestureRecognizerStateChanged) { // 添加直線 [self.path addLineToPoint:curP]; // 重繪 [self setNeedsDisplay]; }}4. 繪制, 遍歷數(shù)組中的路徑,判斷是否是圖片,如果是圖片則將圖片繪制上去,反之為路徑,直接繪制路徑
// 繪制- (void)drawRect:(CGRect)rect { // 變量路徑數(shù)組重繪 for (LDBezierPath *path in self.pathArray) { if (path.class == [UIImage class]) { UIImage *image = (UIImage *)path; [image drawInRect:rect]; NSLog(@"%@", image); } else { [path.lineColor set]; [path stroke]; } }}5. 圖片保存
// 保存- (void)save{ if (self.pathArray.count) { // 1.開啟位圖上下文 UIGraphicsBeginImageContextWithOptions(self.bounds.size, NO, 0); // 2.獲取當(dāng)前上下文 CGContextRef ref = UIGraphicsGetCurrentContext(); // 3.將view的layer渲染到位圖上下文總 [self.layer renderInContext:ref]; // 4.獲取位圖上下文中的image UIImage *image = UIGraphicsGetImageFromCurrentImageContext(); // 5.關(guān)閉位圖上下文 UIGraphicsEndImageContext(); // 6.將圖片保存到相冊 UIImageWriteToSavedPhotosAlbum(image, self, @selector(image:didFinishSavingWithError:contextInfo:), nil); } else { [MBProgressHUD showError:@"沒有圖片可保存"]; } }- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo{ [MBProgressHUD showSuccess:@"保存成功"];}
轉(zhuǎn)載于:https://www.cnblogs.com/Xfsrn/p/5000349.html
總結(jié)
以上是生活随笔為你收集整理的iOS开发核心动画之画图板的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。