自定義驗(yàn)證碼視圖(OC)

混淆的驗(yàn)證碼視圖,是我們?nèi)粘=?jīng)常用到的功能模塊之一,一般來(lái)說(shuō)后臺(tái)不會(huì)直接返回我們驗(yàn)證碼的圖片,一般需要我們將字符串信息轉(zhuǎn)換成我們需要的視圖;不管是轉(zhuǎn)換成View還是button,這里介紹一個(gè)比較簡(jiǎn)單的方法,重寫

- (void)drawRect:(CGRect)rect

這里一般需要兩個(gè)步驟,一是重寫字符串的字體大小、顏色、樣式等
首先計(jì)算每個(gè)字符顯示的位置

    NSString *text  =  [NSString stringWithFormat:@"%@", self.verifyCode];
    
    CGSize cSize  =  [@"A" sizeWithAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:20]}];
    
    int width  =  rect.size.width/text.length - cSize.width;
    int height  =  rect.size.height - cSize.height;

設(shè)置字符串的字體大小、顏色

 for ( int i  =  0; i<text.length; i++)
    {
        pX  =  arc4random() % width + rect.size.width/text.length * i;
        pY  =  arc4random() % height;
        point  =  CGPointMake(pX, pY);
        
        unichar c  =  [text characterAtIndex:i];
        NSString *textC  =  [NSString stringWithFormat:@"%C", c];
        
        UIFont *randomFont = [UIFont systemFontOfSize:arc4random() % 5 + 15];
        [textC drawAtPoint:point withAttributes:@{NSFontAttributeName : randomFont}];
    }

當(dāng)然這樣還是完全不夠的,還需要我們繪制干擾線

 CGContextRef context  =  UIGraphicsGetCurrentContext();
    //設(shè)置線條寬度
    CGContextSetLineWidth(context, kLineWidth);
    
    //繪制干擾線
    for (int i  =  0; i < kLineCount; i++)
    {
        UIColor *randomColor = [UIColor colorWithRed:arc4random() % 256 / 256.0 green:arc4random() % 256 / 256.0 blue:arc4random() % 256 / 256.0 alpha:1.0];
        CGContextSetStrokeColorWithColor(context, randomColor.CGColor);//設(shè)置線條填充色
        
        //設(shè)置線的起點(diǎn)
        pX  =  arc4random() % (int)rect.size.width;
        pY  =  arc4random() % (int)rect.size.height;
        CGContextMoveToPoint(context, pX, pY);
        //設(shè)置線終點(diǎn)
        pX  =  arc4random() % (int)rect.size.width;
        pY  =  arc4random() % (int)rect.size.height;
        CGContextAddLineToPoint(context, pX, pY);
        //畫線
        CGContextStrokePath(context);
    }
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

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

  • 第5章 引用類型(返回首頁(yè)) 本章內(nèi)容 使用對(duì)象 創(chuàng)建并操作數(shù)組 理解基本的JavaScript類型 使用基本類型...
    大學(xué)一百閱讀 3,270評(píng)論 0 4
  • 1. Java基礎(chǔ)部分 基礎(chǔ)部分的順序:基本語(yǔ)法,類相關(guān)的語(yǔ)法,內(nèi)部類的語(yǔ)法,繼承相關(guān)的語(yǔ)法,異常的語(yǔ)法,線程的語(yǔ)...
    子非魚_t_閱讀 31,778評(píng)論 18 399
  • 混淆的驗(yàn)證碼視圖,是我們?nèi)粘=?jīng)常用到的功能模塊之一,一般來(lái)說(shuō)后臺(tái)不會(huì)直接返回我們驗(yàn)證碼的圖片,一般需要我們將字符串...
    hoggenWang閱讀 342評(píng)論 0 0
  • 我是一個(gè)比較內(nèi)向的人,一直都很喜歡用文字來(lái)表達(dá)自己的感情,無(wú)論喜、怒、哀、樂(lè)。 最近開始嘗試著在簡(jiǎn)書這個(gè)平...
    海璇閱讀 270評(píng)論 0 2
  • 又是一年金榜題名時(shí),幾家歡喜幾家愁。 李二嬸家的老三后天請(qǐng)客,張大爺家的孫女下個(gè)星期一辦酒。哎呀,這些伢們好爭(zhēng)氣呀...
    淺淺共閱圈閱讀 482評(píng)論 3 7