猫猫分享,必须精品
原创文章,欢迎转载。转载请注明:翟乃玉的博客 地址:?viewmode=contents 源码:
效果:
实现过程:
首先用storyboard搭建界面,没有什么好说的。 然后就是注意的功能了,这里用了触摸事件来搭配Quartz2D的路径来画画。 思路就是把路径放到数组中
@property (nonatomic, strong) NSMutableArray *paths;
这里注意 如果用c语言的这个方式
CGMutablePathRef path = CGPathCreateMutable();CGPathMoveToPoint(path, NULL, 20, 20);CGPathAddLineToPoint(path, NULL, 100, 100);
画的话,是不能放到oc的数组中的,所以用了UIBezierPath创建一个路径对象。
UIBezierPath *path = [UIBezierPath bezierPath];
然后就是把路径放到数组中,渲染
注意:刚刚开始我没有调用重绘方法,然后悲剧了,,啥都没有。郁闷老半天。 重绘: 调用drawRect方法重回视图
[self setNeedsDisplay];代码实现
开始触摸:
// 开始触摸- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{// 1.获取手指对应UITouch对象UITouch *touch = [touches anyObject];// 2.通过UITouch对象获取手指触摸的位置CGPoint startPoint = [touch locationInView:touch.view];// 3.当用户手指按下的时候创建一条路径UIBezierPath *path = [UIBezierPath bezierPath];// 3.1设置路径的相关属性[path setLineJoinStyle:kCGLineJoinRound];[path setLineCapStyle:kCGLineCapRound];[path setLineWidth:10];// 4.设置当前路径的起点[path moveToPoint:startPoint];// 5.将路径添加到数组中[self.paths addObject:path];}
移动:
// 移动- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event{// 1.获取手指对应UITouch对象UITouch *touch = [touches anyObject];// 2.通过UITouch对象获取手指触摸的位置CGPoint movePoint = [touch locationInView:touch.view];// 3.取出当前的pathUIBezierPath *currentPaht = [self.paths lastObject];// 4.设置当前路径的终点[currentPaht addLineToPoint:movePoint];// 6.调用drawRect方法重回视图[self setNeedsDisplay];}
回退和清屏方法:
– (void)clearView{[self.paths removeAllObjects];[self setNeedsDisplay];}- (void)backView{[self.paths removeLastObject];[self setNeedsDisplay];}
画线方法就是遍历数组中的UIBezierPath对象来实现
// 画线- (void)drawRect:(CGRect)rect{[[UIColor redColor] set];) {[path stroke];}}
可以以心感悟,以此沉淀,足矣;耳听佳音,目极美好,