iOS使用CIFilter生成二维码

2020-01-21 03:44:38王冬梅

打开 Main.storyboard 文件,从对象库中找到点击手势(Tap Gesture Recognizer),将其添加到视图控制器的Image View上,完成之后会在控制器的顶部看到它:

iOS,生成二维码,CIFilter生成二维码

打开辅助编辑器,将其连接到代码中:

iOS,生成二维码,CIFilter生成二维码

为了使image View能响应手势操作,需要在 viewDidLoad 中设置image View的 userInteractionEnabled 属性:


- (void)viewDidLoad
{
  ...
  self.imageView.userInteractionEnabled = YES;
}

然后在实现部分找到 tap: 方法,并添加下面的代码:


- (IBAction)tap:(id)sender
{
  // 添加提示框
  UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"Save QRCode?" message:@"The QRCode will be saved in Camera Roll album." preferredStyle:UIAlertControllerStyleAlert];
  
  UIAlertAction *saveAction = [UIAlertAction actionWithTitle:@"Save" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
    // 保存二维码图像
    [self saveQRCodeImage];
  }];
  UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleCancel handler:nil];
  
  [alertController addAction:saveAction];
  [alertController addAction:cancelAction];
  
  [self presentViewController:alertController animated:YES completion:nil];
}

这时编译器会有红色警告提示 saveQRCodeImage 方法未声明。接下来我们就在实现部分添加该方法来实现二维码的保存:


- (void)saveQRCodeImage
{
  // 绘制图像
  UIGraphicsBeginImageContext(self.imageView.image.size);
  [self.imageView.image drawInRect:self.imageView.bounds];
  self.imageView.image = UIGraphicsGetImageFromCurrentImageContext();
  UIGraphicsEndImageContext();
  
  // 保存图像
  UIImageWriteToSavedPhotosAlbum(self.imageView.image, nil, nil, nil);
}

值得说明的是,这里的 self.imageView.image 是从CIImage对象转换来的,是保存不到相册的,需要先在图形上下文中绘制一下,生成一个新的图像,然后才能保存。

此时,运行程序,点击生成的二维码图像你会看到下面的效果:

iOS,生成二维码,CIFilter生成二维码

但是点击 Save 按钮时,程序会崩溃,在控制台会看到下面的消息:

This app has crashed because it attempted to access privacy-sensitive data without a usage description. The app's Info.plist must contain an NSPhotoLibraryAddUsageDescription key with a string value explaining to the user how the app uses this data.