亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定

iOS開發之用兩段代碼創建二維碼

標簽:
Android iOS

关于二维码生成,网上也是有很多,很早以前的第三方库大多数都是通过C++写,也是有的如zxing,也是挺好用,这里介绍的是通过CIFilter创建二维码。
创建二维码非常简单,只要传入简单的字符串就好了

- (CIImage *)createQRForString:(NSString *)qrString {

    NSData *stringData = [qrString dataUsingEncoding:NSUTF8StringEncoding];

    // 创建filter

    CIFilter *qrFilter = [CIFilter filterWithName:@"CIQRCodeGenerator"];

    // 设置内容和纠错级别

    [qrFilter setValue:stringData forKey:@"inputMessage"];

    [qrFilter setValue:@"M" forKey:@"inputCorrectionLevel"];

    // 返回CIImage

    return qrFilter.outputImage;

为生成的二维码是一个CIImage,我们直接转换成UIImage的话大小不好控制,所以使用下面方法返回需要大小的UIImage:

- (UIImage *)createNonInterpolatedUIImageFormCIImage:(CIImage *)image withSize:(CGFloat) size {

    CGRect extent = CGRectIntegral(image.extent);

    CGFloat scale = MIN(size/CGRectGetWidth(extent), size/CGRectGetHeight(extent));

   // 1.创建bitmap;

    size_t width = CGRectGetWidth(extent) * scale;

    size_t height = CGRectGetHeight(extent) * scale;

    CGColorSpaceRef cs = CGColorSpaceCreateDeviceGray();

    CGContextRef bitmapRef = CGBitmapContextCreate(nil, width, height, 8, 0, cs, (CGBitmapInfo)kCGImageAlphaNone);

    CIContext *context = [CIContext contextWithOptions:nil];

    CGImageRef bitmapImage = [context createCGImage:image fromRect:extent];

    CGContextSetInterpolationQuality(bitmapRef, kCGInterpolationNone);

    CGContextScaleCTM(bitmapRef, scale, scale);

    CGContextDrawImage(bitmapRef, extent, bitmapImage);

    // 2.保存bitmap到图片

    CGImageRef scaledImage = CGBitmapContextCreateImage(bitmapRef);

    CGContextRelease(bitmapRef); 

    CGImageRelease(bitmapImage);

    //原图

    UIImage *outputImage = [UIImage imageWithCGImage:scaledImage];

    UIGraphicsBeginImageContextWithOptions(outputImage.size, NO, [[UIScreen mainScreen] scale]);

    [outputImage drawInRect:CGRectMake(0,0 , size, size)];

    //水印图

    UIImage *waterimage = [UIImage imageNamed:@"icon"];

    [waterimage drawInRect:CGRectMake((size-waterImagesize)/2.0, (size-waterImagesize)/2.0, waterImagesize, waterImagesize)];

    UIImage *newPic = UIGraphicsGetImageFromCurrentImageContext();

    UIGraphicsEndImageContext();

    return newPic;

}
點擊查看更多內容
6人點贊

若覺得本文不錯,就分享一下吧!

評論

作者其他優質文章

正在加載中
Web前端工程師
手記
粉絲
57
獲贊與收藏
1768

關注作者,訂閱最新文章

閱讀免費教程

感謝您的支持,我會繼續努力的~
掃碼打賞,你說多少就多少
贊賞金額會直接到老師賬戶
支付方式
打開微信掃一掃,即可進行掃碼打賞哦
今天注冊有機會得

100積分直接送

付費專欄免費學

大額優惠券免費領

立即參與 放棄機會
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號

舉報

0/150
提交
取消