最近在學習一些動畫的效果,其中有一個功能 可以手動繪製圖像,比如 畫板的實現。
在瞭解其實現原理之後實現起來還是比較簡單的
代碼如下:
@interface DrawView : UIView
@end
//
// DrawView.m
// QuarteCore
//
// Created by HAOZO.MAC on 15/4/14.
// Copyright (c) 2015年 HAOZO.MAC. All rights reserved.
//
#import "DrawView.h"
@interface DrawView ()
@property(nonatomic,strong)NSMutableArray *arrays;
@property(assign,nonatomic)CGMutablePathRef drawPath;
@end
@implementation DrawView
// 每次都是完整的繪製視圖中需要繪製部分中的內容
- (void)drawRect:(CGRect)rect {
CGContextRef context=UIGraphicsGetCurrentContext();
[self drawView:context];
}
-(void)drawView:(CGContextRef)context{
// CGContextMoveToPoint(context, self.preLocation.x, self.preLocation.y);
// CGContextAddLineToPoint(context, self.location.x, self.location.y);
// 首先將數組中的路徑全部繪製出來
for (UIBezierPath *path in self.arrays) {
CGContextAddPath(context, path.CGPath);
[[UIColor redColor]set];
CGContextSetLineWidth(context, 10.0f);
CGContextSetLineCap(context, kCGLineCapRound);
CGContextDrawPath(context, kCGPathStroke);
}
CGContextAddPath(context, self.drawPath);
[[UIColor redColor]set];
CGContextSetLineWidth(context, 30.0f);
CGContextSetLineCap(context, kCGLineCapRound);
CGContextDrawPath(context, kCGPathStroke);
}
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
UITouch *touch=[touches anyObject];
CGPoint point=[touch locationInView:self];
self.drawPath=CGPathCreateMutable();
CGPathMoveToPoint(self.drawPath, NULL, point.x, point.y);
}
-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event{
// 可以獲取到用戶當前觸摸到的點
UITouch *touch=[touches anyObject];
CGPoint point=[touch locationInView:self];
// 添加到路徑中
CGPathAddLineToPoint(self.drawPath, NULL, point.x, point.y);
[self setNeedsDisplay];
}
-(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event{
// 一筆畫完,將完整的路徑添加到路徑數組中
if (!self.arrays) {
self.arrays=[[NSMutableArray alloc]init];
}
UIBezierPath *bezier=[UIBezierPath bezierPathWithCGPath:self.drawPath];
// 需要記錄當前繪製路徑的顏色和線寬 可以自定義一個類來封裝處理
[self.arrays addObject:bezier];
CGPathRelease(self.drawPath);
}
@end
==================
調用:
DrawView *draw=[[DrawView alloc]initWithFrame:self.view.bounds];
draw.backgroundColor=[UIColor whiteColor];
[self.view addSubview:draw];