• 浅说iOS二维码的那些事儿


    1. 二维码需要用到 Quartz 2D 一般是三步走~1导入CoreImage框架,编写字符串转二维码图;2渲染二维码;3显示二维码.
      导入头文件
      #import <CoreImage/CoreImage.h>

    2. 字符转二维码图
      代码如下:

    /**
     *  创建二维码
     *
     *  @param string string 输入待转二维码的字符串
     *
     *  @return 二维码
     */
    - (CIImage *)createTwoDimensionCodeWithString:(NSString *)string {
        
        CIFilter *filter = [CIFilter filterWithName:@"CIQRCodeGenerator"];
        
        [filter setDefaults];
        
        NSData *data = [ string dataUsingEncoding:NSUTF8StringEncoding];
        
        [filter setValue:data forKey:@"inputMessage"];
        
        CIImage *image = [filter outputImage];
        
        return image;
    }
    

    3.渲染改变

    	
    /**
     *  改变图片渲染
     *
     *  @param image 待渲染的二维码图片
     *  @param size  渲染大小
     *
     *  @return 返回渲染的二维码
     */
    
    
    - (UIImage *)createNonInterpolatedUIImageFormCIImage:(CIImage *)image withSize:(CGFloat) size {
        CGRect extent = CGRectIntegral(image.extent);
        //设置比例
        CGFloat scale = MIN(size/CGRectGetWidth(extent), size/CGRectGetHeight(extent));
        // 创建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);
        // 保存bitmap到图片
        CGImageRef scaledImage = CGBitmapContextCreateImage(bitmapRef);
        CGContextRelease(bitmapRef);
        CGImageRelease(bitmapImage);
        return [UIImage imageWithCGImage:scaledImage];
    }
    
    
    
    

    4.显示二维码

    - (void)viewDidLoad {
        [super viewDidLoad];
        // Do any additional setup after loading the view, typically from a nib.
        
       CIImage *image = [self createTwoDimensionCodeWithString:@"爱我你怕了吗?"];
       // CIImage *image = [self createTwoDimensionCodeWithString:@"www.baidu.com"];
        UIImage *img = [self createNonInterpolatedUIImageFormCIImage:image withSize:300];
        UIImageView *imgView = [[UIImageView alloc]initWithImage:img];
        imgView.frame = CGRectMake(10, 50, 300, 300);
        [self.view addSubview:imgView];
    }
    
  • 相关阅读:
    grpc源码分析之域名解析
    使用swig工具为go语言与c++进行交互
    使用VS2015编译grpc_1.3.1
    在linux中编译grpc
    win32网络模型之重叠I/O
    滚动动画animate-scroll扩展
    Android Studio Gradle更新的解决办法
    MUI——页面的创建、显示、关闭
    VS2013中使用QT插件后每次重新编译问题
    Oracle Rman恢复
  • 原文地址:https://www.cnblogs.com/jiahao89/p/5503671.html
Copyright © 2020-2023  润新知