#import "PWDView.h"
@interface PWDView ()
//保存路径
@property(nonatomic,strong)NSMutableArray *pathArray;
//临时路径 拖拽过程中的路径 不会放到路径数组中
@property(nonatomic,strong)UIBezierPath *tempPath;
@end
@implementation PWDView
{
//判断一开始是否选中一个节点
BOOL _isSelectStartPoint;
//起点
CGPoint _startPoint;
//结束点
CGPoint _endPoint;
}
/** 懒加载pathArray */
- (NSMutableArray *)pathArray{
if (!_pathArray) {
_pathArray = [NSMutableArray array];
}
return _pathArray;
}
- (void)awakeFromNib
{ //布局点
[self allViews];
}
/** 布局九个点 */
- (void)allViews{
//高
CGFloat height = 50;
//宽
CGFloat width = 50;
//行间距
CGFloat widthclip = (375 - 150) / 4;
//列间距
CGFloat heightclip = (500 - 150) / 4;
//循环添加
for (int i = 0; i<3; i++) {
for (int j = 0; j<3; j++) {
UIView *v = [[UIView alloc]init];
v.frame = CGRectMake(widthclip + (widthclip + width) * i, heightclip +(heightclip +height) * j, width, height);
v.backgroundColor = [UIColor blackColor];
v.layer.cornerRadius = width / 2;
[self addSubview:v];
}
}
}
/** 开始触摸 */
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
//清空状态
[self.pathArray removeAllObjects];
for (UIView *v in self.subviews) {
v.backgroundColor = [UIColor blackColor];
v.userInteractionEnabled = YES;
}
//拿到触摸起点
_startPoint = [[touches anyObject] locationInView:self];
//检测接触到屏幕的点是否在节点上
for (UIView *v in self.subviews) {
//判断是否在节点内
if (CGRectContainsPoint(v.frame, _startPoint)) {
//改变节点背景
v.backgroundColor = [UIColor purpleColor];
//开始选中了第一个节点
_isSelectStartPoint = YES;
//把开始触摸点改到节点的中心点
_startPoint = v.center;
//关闭交互 不能被再次选中
v.userInteractionEnabled = NO;
}
}
}
/** 触摸中 */
- (void)touchesMoved:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
//拿到移动过程中最后一点
_endPoint = [[touches anyObject] locationInView:self];
//判断是否在第一个节点 如果有 继续
if (_isSelectStartPoint) {
//创建当前路径
self.tempPath = [UIBezierPath bezierPath];
//将开始点赋值给路径
[self.tempPath moveToPoint:_startPoint];
//将移动中的点赋值给路径
[self.tempPath addLineToPoint:_endPoint];
//渲染 调用drawRect方法
[self setNeedsDisplay];
//检测移动接触到屏幕的点是否到了节点上
for (UIView *v in self.subviews) {
//判断是否在节点内
if (CGRectContainsPoint(v.frame, _endPoint) && v.userInteractionEnabled) {
//重新生成路径
self.tempPath = [UIBezierPath bezierPath];
//给出路径的起点
[self.tempPath moveToPoint:_startPoint];
//将节点的中心点作为结束点
[self.tempPath addLineToPoint:v.center];
//将路径放入数组
[self.pathArray addObject:self.tempPath];
v.userInteractionEnabled = NO;
//将最新选中的节点的中心点作为下一个路径的起点
_startPoint = v.center;
//改变新节点背景
v.backgroundColor = [UIColor purpleColor];
}
}
}
}
/** 结束触摸 */
- (void)touchesEnded:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
self.tempPath = nil;
[self setNeedsDisplay];
_isSelectStartPoint = NO;
}
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
// Drawing code
// 绘制所有路径
for (UIBezierPath *path in self.pathArray ) {
path.lineWidth = 5;
[path stroke];
}
self.tempPath.lineWidth = 5;
[self.tempPath stroke];
}
@end
网友评论