//
// MyCutomView.m
// QuartzCoreTest
//
// Created by qianyb on 15/4/9.
// Copyright (c) 2015年 vic. All rights reserved.
//
#import "MyCutomView.h"
@implementation MyCutomView{
//保存之前触摸接触的点
NSMutableArray *lines;
//临时保存本次触摸所有接触的点
NSMutableArray *pointsTemp;
}
- (instancetype)init{
if (self = [super init]) {
lines = [NSMutableArray array];
pointsTemp = [NSMutableArray array];
return self;
}
return nil;
}
/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
*/
- (void)drawRect:(CGRect)rect {
//使用UIKit提供的函数获取当前操作的context
CGContextRef context = UIGraphicsGetCurrentContext();
//设置线条帽样式
CGContextSetLineCap(context, kCGLineCapRound);
//设置线条连接处的样式
CGContextSetLineJoin(context, kCGLineJoinRound);
//设置线条粗细
CGContextSetLineWidth(context, 5);
//设置颜色
CGContextSetRGBStrokeColor(context, 1, 0, 0, 1);
for (NSArray *arr in lines) {
//开始一个起始路径 绘制之前触摸所有的点
//注意:每一次触摸为一个路径,这样调用CGContextStrokePath()函数连接点时,才不会产生“连笔”
CGContextBeginPath(context);
for (int i = 0 ; i < arr.count; i ++) {
CGPoint point = CGPointFromString(arr[i]);
if (i == 0) {
//起始点设置为(0,0):注意这是上下文对应区域中的相对坐标,
CGContextMoveToPoint(context, point.x, point.y);
}else{
//设置下一个坐标点
CGContextAddLineToPoint(context, point.x, point.y);
}
}
//连接上面定义的坐标点
CGContextStrokePath(context);
}
//重新开始一个起始路径,绘制当前触摸所有的点
CGContextBeginPath(context);
for (int i = 0; i < pointsTemp.count; i++) {
CGPoint point = CGPointFromString(pointsTemp[i]);
if (i == 0) {
//起始点设置为(0,0):注意这是上下文对应区域中的相对坐标,
CGContextMoveToPoint(context, point.x, point.y);
}else{
//设置下一个坐标点
CGContextAddLineToPoint(context, point.x, point.y);
}
}
//连接上面定义的坐标点
CGContextStrokePath(context);
}
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event{
UITouch *touch = [touches anyObject];
CGPoint point = [touch locationInView:self];
//保存数据
[pointsTemp addObject:NSStringFromCGPoint(point)];
//通知View需要重新渲染,会触发drawRect:方法的调用
[self setNeedsDisplay];
}
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event{
//保存本次触摸所有的点
[lines addObject:pointsTemp];
//清空以便下次触摸时保存数据
pointsTemp = [NSMutableArray array];
}
@end