直接贴源码了
#import "WNDrawView.h"
@interface WNDrawView()
@property(nonatomic,strong)NSMutableArray*dataArray;
@end
@implementation WNDrawView
{
CGPoint _currentPoint;
}
//对应xib的类不会进入该方法
-(instancetype)initWithFrame:(CGRect)frame{
if (self=[super initWithFrame:frame]) {
}
return self;
}
-(void)awakeFromNib{
[self addGestureRecognizer:[[UIPanGestureRecognizer alloc]initWithTarget:self action:@selector(panClick:)]];
//创建9个btn
for (int i=0; i<9; i++) {
UIButton*btn=[UIButton buttonWithType:UIButtonTypeCustom];
[self addSubview:btn];
btn.tag=i;
[btn setImage:[UIImage imageNamed:@"gesture_node_normal"] forState:UIControlStateNormal];
[btn setImage:[UIImage imageNamed:@"gesture_node_highlighted"] forState:UIControlStateSelected];
}
}
//在这个里面拿到的父控件的尺寸才是最准确的
-(void)layoutSubviews{
NSUInteger count=self.subviews.count;
CGFloat width=74.0f;
CGFloat height=width;
CGFloat gapW=(375-width*3)/4;
CGFloat gapH=(400-height*3)/4;
for (NSUInteger i=0; i<count; i++) {
UIButton*btn=self.subviews[i];
//行
CGFloat row=i/3;
//列
CGFloat col=i%3;
btn.frame=CGRectMake((width+gapW)*col+gapW, gapH+(gapH+height)*row, width, height);
}
}
#pragma mark - 按钮点击
-(void)panClick:(UIPanGestureRecognizer*)pan{
_currentPoint=[pan locationInView:self];
for (UIButton*btn in self.subviews) {
if (CGRectContainsPoint(btn.frame, _currentPoint)&&![self.dataArray containsObject:btn]) {
btn.selected=YES;
[self.dataArray addObject:btn];
//如果放在里面就只是选中的时候才会划线
}
}
if (pan.state==UIGestureRecognizerStateEnded) {
NSMutableString*str=[NSMutableString string];
for (UIButton*btn in self.dataArray) {
[str appendFormat:@"%ld",btn.tag];
}
NSLog(@"%@",str);
//让选中状态全部取消。然后绘制的话,线自然就全都清除了
// [self.dataArray makeObjectsPerformSelector:@selector(setSelected:) withObject:@(NO)];
for (UIButton* btn in self.dataArray ) {
[btn setSelected:NO];
}
//然后删除数组中的所有元素。下次再次添加锁屏的时候数组为空
[self.dataArray removeAllObjects];
}
[self setNeedsDisplay];
}
-(void)drawRect:(CGRect)rect{
if(self.dataArray.count==0)return;
UIBezierPath*path=[UIBezierPath bezierPath];
for (int i=0; i<self.dataArray.count; i++) {
UIButton*btn=self.dataArray[i];
if (i==0) {
[path moveToPoint:btn.center];
}else{
[path addLineToPoint:btn.center];
}
}
[path addLineToPoint:_currentPoint];
//stroke相关
path.lineWidth=10;
path.lineJoinStyle=kCGLineJoinRound;
[[UIColor greenColor] setStroke];
[path stroke];
}
#pragma mark - getter&setter
-(NSMutableArray *)dataArray{
if (_dataArray==nil) {
_dataArray=[NSMutableArray array];
}
return _dataArray;
}