iOS:九宮格圖案鎖

問題:項(xiàng)目需要自定義一個(gè)九宮格圖案鎖
解決問題:首先我們自定義一個(gè)LockView繼承UIView
我們要做的就是在這個(gè)LockView中去鋪設(shè)我們的9宮格圖案
LockView.m中

// tag基數(shù)
#define BaseTag     10000
@interface LockView () {
    
    NSMutableArray* _circleArray;//鋪設(shè)的button
    NSMutableArray* _selectedCircleArray;//已選擇的button
    CGPoint nowPoint;//當(dāng)前觸摸位置
    
    BOOL isWrongColor;// 標(biāo)記是否正在顯示錯(cuò)誤的繪圖
    BOOL isDrawing;     // 標(biāo)記是否正在繪圖中
    
    UIColor *tempLineColor; //臨時(shí)的連接線的顏色
    UIColor *wrongColor;//檔圖案錯(cuò)誤的時(shí)候顯示的顏色
    UIColor *themeColor;//button未選擇時(shí)顯示的顏色
    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 是因?yàn)?button有selected這個(gè)屬性 用起來比較方便
        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從基數(shù)+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];
}


//在這里我們?nèi)ミB接路徑
- (void)drawRect:(CGRect)rect {
    if (_selectedCircleArray.count) {
        UIBezierPath *path = [UIBezierPath bezierPath];
        for (int i = 0; i < _selectedCircleArray.count; i++) {
            
            //如果說按鈕是第一個(gè),讓按鈕的中心點(diǎn)是路徑的起點(diǎn)
            UIButton *btn = _selectedCircleArray[i];
            if (i == 0) {
                [path moveToPoint:btn.center];
            } else {
                [path addLineToPoint:btn.center];
            }
        }
        
        if (!isWrongColor) {
            
            //添加一根線到當(dāng)前手指所在的點(diǎn)
            [path addLineToPoint:nowPoint];
            //讓線頭看起來圓滑一點(diǎn)
            UIBezierPath * rounds=[UIBezierPath bezierPathWithRoundedRect:CGRectMake(nowPoint.x-lineWidth/2, nowPoint.y-lineWidth/2, lineWidth, lineWidth) cornerRadius:lineWidth/2];
            //渲染
            [[UIColor greenColor] setFill];
            [rounds fill];
        }
        
        //設(shè)置線的狀態(tài)

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

//當(dāng)手指移動時(shí)判斷是否在九宮格button上
- (void)updatePositionWithTouches:(NSSet *)touches{

    
    //記錄當(dāng)前手指的位置
    UITouch *touch = [touches anyObject];
    CGPoint curP = [touch locationInView:self];
    nowPoint = curP;
    
    //判斷當(dāng)前點(diǎn)在不在按鈕身上  如果按鈕不為空 保存選中的按鈕
    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];
    }
//這個(gè)string 就是我們解鎖圖案數(shù)字的排列順序
    [self.delegate sendLockString:string];//這里是我們的代理 用來把排列順序string傳遞到我們的父視圖
//也可以在這里判斷
if ([string isEqualToString:self.rightString]) {
        ....
    }else{
        //這里我直接當(dāng)錯(cuò)誤處理
    [self showErrorCircles:string];
    }


}

/**
 清除至初始狀態(tài)
 */
- (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]; // 數(shù)字是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); //添加一個(gè)圓
    CGContextDrawPath(context, kCGPathStroke); //繪制路徑
    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
    //關(guān)閉圖形上下文
    UIGraphicsEndImageContext();
    
    return newImage;
}

在LockView.h中來寫我們的協(xié)議

@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
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市顶籽,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌极谊,老刑警劉巖,帶你破解...
    沈念sama閱讀 219,539評論 6 508
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件仰剿,死亡現(xiàn)場離奇詭異虾标,居然都是意外死亡蔓腐,警方通過查閱死者的電腦和手機(jī)叮阅,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,594評論 3 396
  • 文/潘曉璐 我一進(jìn)店門刁品,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人浩姥,你說我怎么就攤上這事挑随。” “怎么了勒叠?”我有些...
    開封第一講書人閱讀 165,871評論 0 356
  • 文/不壞的土叔 我叫張陵兜挨,是天一觀的道長。 經(jīng)常有香客問我眯分,道長拌汇,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 58,963評論 1 295
  • 正文 為了忘掉前任弊决,我火速辦了婚禮担猛,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘丢氢。我一直安慰自己,他們只是感情好先改,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,984評論 6 393
  • 文/花漫 我一把揭開白布疚察。 她就那樣靜靜地躺著,像睡著了一般仇奶。 火紅的嫁衣襯著肌膚如雪貌嫡。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 51,763評論 1 307
  • 那天该溯,我揣著相機(jī)與錄音岛抄,去河邊找鬼。 笑死狈茉,一個(gè)胖子當(dāng)著我的面吹牛夫椭,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播氯庆,決...
    沈念sama閱讀 40,468評論 3 420
  • 文/蒼蘭香墨 我猛地睜開眼蹭秋,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了堤撵?” 一聲冷哼從身側(cè)響起仁讨,我...
    開封第一講書人閱讀 39,357評論 0 276
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎实昨,沒想到半個(gè)月后洞豁,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,850評論 1 317
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 38,002評論 3 338
  • 正文 我和宋清朗相戀三年丈挟,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了刁卜。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 40,144評論 1 351
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡礁哄,死狀恐怖长酗,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情桐绒,我是刑警寧澤夺脾,帶...
    沈念sama閱讀 35,823評論 5 346
  • 正文 年R本政府宣布,位于F島的核電站茉继,受9級特大地震影響咧叭,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜烁竭,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,483評論 3 331
  • 文/蒙蒙 一菲茬、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧派撕,春花似錦婉弹、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,026評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至际跪,卻和暖如春商佛,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背姆打。 一陣腳步聲響...
    開封第一講書人閱讀 33,150評論 1 272
  • 我被黑心中介騙來泰國打工良姆, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人幔戏。 一個(gè)月前我還...
    沈念sama閱讀 48,415評論 3 373
  • 正文 我出身青樓玛追,卻偏偏與公主長得像,于是被迫代替她去往敵國和親闲延。 傳聞我的和親對象是個(gè)殘疾皇子豹缀,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,092評論 2 355

推薦閱讀更多精彩內(nèi)容

  • 1、通過CocoaPods安裝項(xiàng)目名稱項(xiàng)目信息 AFNetworking網(wǎng)絡(luò)請求組件 FMDB本地?cái)?shù)據(jù)庫組件 SD...
    陽明先生_X自主閱讀 15,982評論 3 119
  • 研二科研狗一枚慨代,不邢笙,準(zhǔn)確說這學(xué)期我們是研三了。還有半個(gè)學(xué)期侍匙,就快畢業(yè)了氮惯《vǎ可是學(xué)校居然喜新厭舊,僅剩三個(gè)月時(shí)間也不讓...
    惹你心歡閱讀 147評論 0 0
  • 所謂情商高妇汗,主要是要讓別人高興帘不,克己復(fù)禮,舍生取義杨箭,壓抑甚至犧牲自己寞焙,成全別人,這類人一般道德情操高尚互婿,即使智商不...
    鷺風(fēng)閱讀 710評論 2 2
  • 雅丹與沙-王彩霞(美麗) 冒著迷路的風(fēng)險(xiǎn)去看你捣郊,為的就是你那迷人的姿態(tài),無法想象在這荒無人煙的地方頑強(qiáng)的堅(jiān)守自...
    雪花琵琶閱讀 246評論 0 3