国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 系統 > iOS > 正文

iOS開發實現隨機圖片驗證碼封裝

2020-07-26 02:44:22
字體:
來源:轉載
供稿:網友

在 iOS 開發中,為了防止短信驗證碼的惡意獲取,注冊時需要圖片驗證,比如某共享單車 APP 在注冊時就用了圖片驗證碼,如下圖:

圖片驗證碼封裝思路:

第一眼看到圖片驗證碼,可能會覺得圖片驗證碼是由 UIImage 實現的,但事實上明顯不是,這里簡單說下圖片驗證碼封裝思路。

  1. 首先要有一個數組,里面包含 1-9、a-z 這些字符
  2. 在 UIView 上顯示這些字符
  3. 同時在 UIView 上繪制干擾線

效果圖

圖片驗證碼效果圖

用法

  _testView = [[NNValidationView alloc] initWithFrame:CGRectMake((self.view.frame.size.width - 100) / 2, 200, 100, 40) andCharCount:4 andLineCount:4];  [self.view addSubview:_testView];

以上兩行代碼便可以實現圖片驗證碼,其中 charCount 和 lineCount 分別指顯示的字符串數量以及干擾線的數量。

另外我們還需要知道圖片驗證碼上的字符串,可以用下邊這個 block 獲取:

 __weak typeof(self) weakSelf = self;  /// 返回驗證碼數字  _testView.changeValidationCodeBlock = ^(void){    NSLog(@"驗證碼被點擊了:%@", weakSelf.testView.charString);  };

打印效果如下

獲取驗證碼數字

核心代碼

#pragma mark - 繪制界面- (void)drawRect:(CGRect)rect {  [super drawRect:rect];  self.backgroundColor = NNRandomColor;  CGFloat rectWidth = rect.size.width;  CGFloat rectHeight = rect.size.height;  CGFloat pointX, pointY;    NSString *text = [NSString stringWithFormat:@"%@",self.charString];  NSInteger charWidth = rectWidth / text.length - 15;  NSInteger charHeight = rectHeight - 25;    // 依次繪制文字  for (NSInteger i = 0; i < text.length; i++) {    // 文字X坐標    pointX = arc4random() % charWidth + rectWidth / text.length * i;    // 文字Y坐標    pointY = arc4random() % charHeight;    unichar charC = [text characterAtIndex:i];    NSString *textC = [NSString stringWithFormat:@"%C", charC];    [textC drawAtPoint:CGPointMake(pointX, pointY) withAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:arc4random() % 10 + 15]}];  }    // 獲取上下文  CGContextRef context = UIGraphicsGetCurrentContext();  // 設置線寬  CGContextSetLineWidth(context, 1.0);    // 依次繪制直線  for(NSInteger i = 0; i < self.lineCount; i++) {    // 設置線的顏色    CGContextSetStrokeColorWithColor(context, NNRandomColor.CGColor);    // 設置線的起點    pointX = arc4random() % (NSInteger)rectWidth;    pointY = arc4random() % (NSInteger)rectHeight;    CGContextMoveToPoint(context, pointX, pointY);    // 設置線的終點    pointX = arc4random() % (NSInteger)rectWidth;    pointY = arc4random() % (NSInteger)rectHeight;    CGContextAddLineToPoint(context, pointX, pointY);    // 繪畫路徑    CGContextStrokePath(context);  }}

代碼中寫了注釋,因此這里不再詳細解釋,需要看全部代碼的童鞋可以點擊下邊的鏈接,有疑問或有建議的話歡迎討論。

demo 地址:NNValidationView

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持武林網。

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 祁阳县| 营口市| 界首市| 广元市| 尼勒克县| 长宁区| 阿勒泰市| 通化县| 东丰县| 怀柔区| 洮南市| 海阳市| 凭祥市| 邵阳县| 基隆市| 鄂托克前旗| 瑞昌市| 建宁县| 广南县| 卢龙县| 天柱县| 富裕县| 临邑县| 天津市| 汝城县| 林甸县| 宾川县| 鄂伦春自治旗| 博客| 浠水县| 桦甸市| 临沭县| 和田县| 宽城| 郴州市| 达尔| 高唐县| 伊春市| 海南省| 和平区| 集安市|