二维码

2017-06-18  本文已影响38人  南冯

NO

生成二维码

1. 创建二维码滤镜
    CIFilter *filter = [CIFilter filterWithName:@"CIQRCodeGenerator"];
    // 恢复默认设置
    [filter setDefaults];
    
    // X 设置二维码的纠错率 一般设置为M 就足够了
    [filter setValue:@"M" forKey:@"inputCorrectionLevel"];
2. 设置滤镜输入数据
    // 'CIQRCodeGenerator filter requires NSData for inputMessage'
// 必须为NSData类型
    NSData *data = [self.textview.text.length > 0 ?self.textview.text : @""  dataUsingEncoding:NSUTF8StringEncoding];
    [filter setValue:data forKey:@"inputMessage"];
3. 从二维码滤镜中获取图片
    CIImage *image = filter.outputImage;
    // 获取到的图片为 23x23  需要对图片进行放大处理
    image = [image imageByApplyingTransform:CGAffineTransformMakeScale(30, 30)];
    // X 添加前景图片
    UIImage *center = [UIImage imageNamed:@"erha"];
    // 4. 显示图片
    UIImage *resultImage = [UIImage imageWithCIImage:image];
    self.codeImageView.image = [self getNewImage:resultImage centerImage:center];

图片重绘

- (UIImage *)getNewImage:(UIImage*)image centerImage:(UIImage *)centerImage{
    // 开启图形上下文
    UIGraphicsBeginImageContext(image.size);
    // 绘制大图片
    [image drawInRect:CGRectMake(0, 0, image.size.width, image.size.height)];
    // 绘制小图片
    [centerImage drawInRect:CGRectMake((image.size.width - 120) * 0.5, (image.size.height - 120) * 0.5, 120, 120)];
    // 从图形上下文中获取图片
    UIImage *resultImage = UIGraphicsGetImageFromCurrentImageContext();
    // 关闭图形上下文
    UIGraphicsEndImageContext();
    return resultImage;

}

从图片中检测二维码

1. 获取要识别的图片
    UIImage *detectImage = self.imageV.image;
    CIImage *iamgeCI = [CIImage imageWithCGImage:detectImage.CGImage];
2. 创建一个二维码探测器
    CIDetector *detector = [CIDetector detectorOfType:CIDetectorTypeQRCode context:nil options:@{CIDetectorAccuracy:CIDetectorAccuracyHigh}];
3. 直接探测二维码特征
    NSArray *fetures = [detector featuresInImage:iamgeCI];
    UIImage *resultimage = detectImage;
    for (CIFeature *feture in fetures) {
        NSLog(@"%@",feture);
        CIQRCodeFeature *QRfeture = (CIQRCodeFeature *)feture;
        NSLog(@"%@",QRfeture.messageString);
        resultimage = [self drawBianKuang:resultimage QRfeture:QRfeture];
        self.imageV.image = resultimage;
    }

图片重绘 注意转换坐标系

- (UIImage *)drawBianKuang:(UIImage *)image QRfeture:(CIQRCodeFeature *)feture{

    // 开启图形上下文
    UIGraphicsBeginImageContext(image.size);
    // 绘制大图
    [image drawInRect:CGRectMake(0, 0, image.size.width,image.size.height)];
    // 绘制边框

    UIBezierPath *path = [UIBezierPath bezierPathWithRect:feture.bounds];
    
    // 转换坐标系(上下颠倒)
    CGContextRef    ref = UIGraphicsGetCurrentContext();
    CGContextScaleCTM(ref, 1, -1);
    CGContextTranslateCTM(ref, 0, -image.size.height);

    // 描边
    path.lineWidth = 6;
    [[UIColor redColor] setStroke];
    [path stroke];
    // 获取图片
    UIImage *resultImgae = UIGraphicsGetImageFromCurrentImageContext();
    // 关闭图形上下文
    UIGraphicsEndImageContext();
    return resultImgae;
}
上一篇下一篇

猜你喜欢

热点阅读