您的位置:首页 > 产品设计 > UI/UE

猫猫学IOS(三十四)UI之Quartz2D画画板的实现

2015-05-06 11:01 615 查看
猫猫分享,必须精品

原创文章,欢迎转载。转载请注明:翟乃玉的博客

地址:http://blog.csdn.net/u013357243?viewmode=contents

源码:/article/1326220.html

效果:



实现过程:

首先用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.取出当前的path
UIBezierPath *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];
// 边路数组绘制所有的线段
for (UIBezierPath *path in self.paths) {
[path stroke];
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: