最近在学习一些动画的效果,其中有一个功能 可以手动绘制图像,比如 画板的实现。
在了解其实现原理之后实现起来还是比较简单的
代码如下:
@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];