iOS:九宫格图案锁

问题:项目需要自定义一个九宫格图案锁
解决问题:首先我们自定义一个LockView继承UIView
我们要做的就是在这个LockView中去铺设我们的9宫格图案
LockView.m中

// tag基数
#define BaseTag     10000
@interface LockView () {
    
    NSMutableArray* _circleArray;//铺设的button
    NSMutableArray* _selectedCircleArray;//已选择的button
    CGPoint nowPoint;//当前触摸位置
    
    BOOL isWrongColor;// 标记是否正在显示错误的绘图
    BOOL isDrawing;     // 标记是否正在绘图中
    
    UIColor *tempLineColor; //临时的连接线的颜色
    UIColor *wrongColor;//档图案错误的时候显示的颜色
    UIColor *themeColor;//button未选择时显示的颜色
    UIColor *lineColor;//连接线的颜色
    UIColor *selectedPointColor;//button选中后颜色
    CGFloat margin;//距离屏幕左右的距离
    CGFloat buttonRaius;//button半径
    CGFloat lineWidth;//连接线的宽度
    CGFloat buttonBorderWidth;//button的连接线宽度
}

@end

@implementation LockView

// 自定义初始化方法
- (instancetype)initLockViewWith:(CGRect)frame forWrongColor:(UIColor *)wrongColor themeColor:(UIColor *)themeColor lineColor:(UIColor *)lineColor selectedPointColor:(UIColor *)selectedPointColor margin:(CGFloat)margin buttonRadius:(CGFloat)buttonRaius lineWidth:(CGFloat)lineWidth buttonBorderWidth:(CGFloat)buttonBorderWidth{
    
    self = [super initWithFrame:frame];
    if (self) {
        self->wrongColor = wrongColor;
        self->themeColor = themeColor;
        self->lineColor = lineColor;
        self->selectedPointColor = selectedPointColor;
        self->margin = margin;
        self->buttonRaius = buttonRaius;
        self->lineWidth = lineWidth;
        self->buttonBorderWidth = buttonBorderWidth;
        tempLineColor = lineColor;
        [self initCircles];
    }
    return self;
}
//初始化9宫格图案
- (void)initCircles {
    
    self.clipsToBounds = YES;
   
    _circleArray = [NSMutableArray array];
    _selectedCircleArray = [NSMutableArray array];
    
    for (int i = 0; i < 9; i++) {
//之所以用button 是因为 button有selected这个属性 用起来比较方便
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        button.frame = CGRectMake(0, 0, buttonRaius*2, buttonRaius*2);
        button.userInteractionEnabled = NO;//禁止用户交互(只做展示不做交互)
        CGFloat pointWidth = (self.frame.size.width-margin*2-buttonRaius*2)/2;
        button.center = CGPointMake(self.center.x + ((i%3)-1)*pointWidth, self.center.y+((i/3)-1)*pointWidth);
        [button setBackgroundImage:[self getCircularSize:button.frame.size borderWith:buttonBorderWidth color:themeColor insideColor:lineColor solid:NO] forState:UIControlStateNormal];
        [button setBackgroundImage:[self getCircularSize:button.frame.size borderWith:buttonBorderWidth color:themeColor insideColor:lineColor solid:YES] forState:UIControlStateSelected];
        button.tag = i + BaseTag + 1; // tag从基数+1开始,
        [self addSubview:button];
        [_circleArray addObject:button];
    }
    self.backgroundColor = [UIColor clearColor];
}

//触摸事件
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
    
    isDrawing = NO;
    
    if (isWrongColor) {
        [self clearColorAndSelectedButton];
    }
    [self updatePositionWithTouches:touches];
    
}

- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
    
    isDrawing = YES;
    [self updatePositionWithTouches:touches];
}

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event{
    
    [self endPosition];
}

- (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event {
    
    [self endPosition];
}


//在这里我们去连接路径
- (void)drawRect:(CGRect)rect {
    if (_selectedCircleArray.count) {
        UIBezierPath *path = [UIBezierPath bezierPath];
        for (int i = 0; i < _selectedCircleArray.count; i++) {
            
            //如果说按钮是第一个,让按钮的中心点是路径的起点
            UIButton *btn = _selectedCircleArray[i];
            if (i == 0) {
                [path moveToPoint:btn.center];
            } else {
                [path addLineToPoint:btn.center];
            }
        }
        
        if (!isWrongColor) {
            
            //添加一根线到当前手指所在的点
            [path addLineToPoint:nowPoint];
            //让线头看起来圆滑一点
            UIBezierPath * rounds=[UIBezierPath bezierPathWithRoundedRect:CGRectMake(nowPoint.x-lineWidth/2, nowPoint.y-lineWidth/2, lineWidth, lineWidth) cornerRadius:lineWidth/2];
            //渲染
            [[UIColor greenColor] setFill];
            [rounds fill];
        }
        
        //设置线的状态

        [path setLineWidth:lineWidth];
        
        [tempLineColor set];
        [path setLineJoinStyle:kCGLineJoinRound];
        [path stroke];
    }
    
}

//当手指移动时判断是否在九宫格button上
- (void)updatePositionWithTouches:(NSSet *)touches{

    
    //记录当前手指的位置
    UITouch *touch = [touches anyObject];
    CGPoint curP = [touch locationInView:self];
    nowPoint = curP;
    
    //判断当前点在不在按钮身上  如果按钮不为空 保存选中的按钮
    UIButton *btn = [self btnContainsPoint:curP];
    
    if (btn && btn.selected == NO) {
        btn.selected = YES;
        [_selectedCircleArray addObject:btn];
    }
    
    [self setNeedsDisplay];
    
}


- (UIButton *)btnContainsPoint:(CGPoint)point
{
    for (UIButton *btn in self.subviews) {
        if (CGRectContainsPoint(btn.frame, point)) {
            return btn;
        }
    }
    return nil;
}

- (void)endPosition {
    isDrawing = NO;
    
    UIButton *strbutton;
    NSString *string=@"";
    
    for (int i=0; i < _selectedCircleArray.count; i++) {
        strbutton = _selectedCircleArray[i];
        string= [string stringByAppendingFormat:@"%ld",(long)strbutton.tag-BaseTag];
    }
//这个string 就是我们解锁图案数字的排列顺序
    [self.delegate sendLockString:string];//这里是我们的代理 用来把排列顺序string传递到我们的父视图
//也可以在这里判断
if ([string isEqualToString:self.rightString]) {
        ....
    }else{
        //这里我直接当错误处理
    [self showErrorCircles:string];
    }


}

/**
 清除至初始状态
 */
- (void)clearColor {
    if (isWrongColor) {// 重置颜色
        isWrongColor = NO;
        tempLineColor = lineColor;

    }
}

- (void)clearSelectedButton {
    for (UIButton *thisButton in _circleArray) {
        [thisButton setSelected:NO];
        [thisButton setBackgroundImage:[self getCircularSize:thisButton.frame.size borderWith:buttonBorderWidth color:themeColor insideColor:selectedPointColor solid:YES] forState:UIControlStateSelected];
    }
    [_selectedCircleArray removeAllObjects];
    
    [self setNeedsDisplay];
}

- (void)clearColorAndSelectedButton {
    if (!isDrawing) {
        [self clearColor];
        [self clearSelectedButton];
        self.userInteractionEnabled = YES;
    }
    
}

#pragma mark - Error Show
- (void)showErrorCircles:(NSString*)string {
    
    isWrongColor = YES;
    tempLineColor = wrongColor;
    NSMutableArray* numbers = [[NSMutableArray alloc] initWithCapacity:string.length];
    for (int i = 0; i < string.length; i++) {
        NSRange range = NSMakeRange(i, 1);
        NSNumber* number = [NSNumber numberWithInt:[string substringWithRange:range].intValue-1]; // 数字是1开始的
        [numbers addObject:number];
        [_circleArray[number.intValue] setSelected:YES];
    }
    
    for (UIButton* button in _circleArray) {
        if (button.selected) {
            [button setBackgroundImage:[self getCircularSize:button.frame.size borderWith:buttonBorderWidth color:themeColor insideColor:tempLineColor solid:YES] forState:UIControlStateSelected];
        }
        
    }

    
    [self setNeedsDisplay];
    self.userInteractionEnabled = NO;
    [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(clearColorAndSelectedButton) userInfo:nil repeats:NO];
    
}
// 生成我们选中和未选中的图片 
-(UIImage *)getCircularSize:(CGSize)size borderWith:(CGFloat)borderWith color:(UIColor *)color insideColor:(UIColor *)insideColor solid:(BOOL)solid{
    UIGraphicsBeginImageContextWithOptions(size, NO, 0);
    
    CGContextRef context = UIGraphicsGetCurrentContext();
    //获取颜色RGB
    CGFloat red = 0.0;
    CGFloat green = 0.0;
    CGFloat blue = 0.0;
    CGFloat alpha = 0.0;
    
    [color getRed:&red green:&green blue:&blue alpha:&alpha];
    CGContextSetRGBStrokeColor(context,red,green,blue,1.0);//画笔线的颜色
    CGContextSetLineWidth(context, borderWith);//线的宽度
    
    if (solid) {
        CGContextAddArc(context, size.width/2, size.height/2, size.width/2-size.width/4, 0, 2*M_PI, 0);
        CGContextSetFillColorWithColor(context, insideColor.CGColor);
        CGContextDrawPath(context, kCGPathFill);//绘制填充
      
    }
    
    CGContextAddArc(context, size.width/2, size.height/2, size.width/2-borderWith, 0, 2*M_PI, 0); //添加一个圆
    CGContextDrawPath(context, kCGPathStroke); //绘制路径
    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
    //关闭图形上下文
    UIGraphicsEndImageContext();
    
    return newImage;
}

在LockView.h中来写我们的协议

@protocol LockViewDelegate
- (void)sendLockString:(NSString *)lockString;
@end
@interface LockView : UIView
- (instancetype)initLockViewWith:(CGRect)frame forWrongColor:(UIColor *)wrongColor themeColor:(UIColor *)themeColor lineColor:(UIColor *)lineColor selectedPointColor:(UIColor *)selectedPointColor margin:(CGFloat)margin buttonRadius:(CGFloat)buttonRaius lineWidth:(CGFloat)lineWidth buttonBorderWidth:(CGFloat)buttonBorderWidth;
@property id<LockViewDelegate>delegate;
@property NSString *rightString;

大功告成


QQ20180912-140117-HD.gif
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 219,490评论 6 508
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 93,581评论 3 395
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 165,830评论 0 356
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,957评论 1 295
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,974评论 6 393
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,754评论 1 307
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,464评论 3 420
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,357评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,847评论 1 317
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,995评论 3 338
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 40,137评论 1 351
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,819评论 5 346
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,482评论 3 331
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 32,023评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 33,149评论 1 272
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,409评论 3 373
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 45,086评论 2 355

推荐阅读更多精彩内容

  • 1、通过CocoaPods安装项目名称项目信息 AFNetworking网络请求组件 FMDB本地数据库组件 SD...
    阳明先生_X自主阅读 15,982评论 3 119
  • 研二科研狗一枚,不,准确说这学期我们是研三了。还有半个学期,就快毕业了。可是学校居然喜新厌旧,仅剩三个月时间也不让...
    惹你心欢阅读 147评论 0 0
  • 所谓情商高,主要是要让别人高兴,克己复礼,舍生取义,压抑甚至牺牲自己,成全别人,这类人一般道德情操高尚,即使智商不...
    鷺風阅读 710评论 2 2
  • 雅丹与沙-王彩霞(美丽) 冒着迷路的风险去看你,为的就是你那迷人的姿态,无法想象在这荒无人烟的地方顽强的坚守自...
    雪花琵琶阅读 246评论 0 3