1.系统生成二维码
//
// ViewController.m
// 实验
//
//
#import "ViewController.h"
@interface ViewController ()
@end
@implementation ViewController
//模糊
- (UIImage *)generateQRCodeFromString:(NSString *)string {
//1. 需要生成二维码的内容
NSData *stringData = [string dataUsingEncoding:NSUTF8StringEncoding];
//2. 二维码生成器
CIFilter *filter = [CIFilter filterWithName:@"CIQRCodeGenerator"];
//3. 设置输入参数
[filter setValue:stringData forKey:@"inputMessage"];
//4. 设置识别率
[filter setValue:@"M" forKey:@"inputCorrectionLevel"];
//5. 获取生成的图片
CGImageRef cgImage = [[CIContext contextWithOptions:nil]createCGImage:[filter outputImage] fromRect:[[filter outputImage]extent]];
return [UIImage imageWithCGImage:cgImage];
}
//清晰
- (UIImage *)image:(UIImage *)image scale:(CGFloat)scale {
CGSize size = image.size;
//1. 缩放图片,使生成的二维码变得更清晰
UIGraphicsBeginImageContext(CGSizeMake(size.width * scale, size.width *scale));
CGContextRef context = UIGraphicsGetCurrentContext();
//2. 插值
CGContextSetInterpolationQuality(context, kCGInterpolationNone);
//3. 绘制图片
CGContextDrawImage(context, CGContextGetClipBoundingBox(context), image.CGImage);
//4. 获取图片
UIImage *preImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
//5. 旋转图片
UIImage *qrImage = [UIImage imageWithCGImage:[preImage CGImage] scale:[preImage scale] orientation:UIImageOrientationDownMirrored];
return qrImage;
}
-(UIImage *)generateQRCodeWithString:(NSString *)string scale:(CGFloat) scale {
NSData *stringData = [string dataUsingEncoding:NSUTF8StringEncoding];
CIFilter *filter = [CIFilter filterWithName:@"CIQRCodeGenerator"];
[filter setValue:stringData forKey:@"inputMessage"];
[filter setValue:@"M" forKey:@"inputCorrectionLevel"];
// Render the image into a CoreGraphics image渲染图像到一个CoreGraphics图像
CGImageRef cgImage = [[CIContext contextWithOptions:nil] createCGImage:[filter outputImage] fromRect:[[filter outputImage]extent]];
//缩放图片,使生成的二维码变得更清晰
UIGraphicsBeginImageContext(CGSizeMake([[filter outputImage]extent].size.width * scale, [filter outputImage].extent.size.width * scale));
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetInterpolationQuality(context, kCGInterpolationNone);
CGContextDrawImage(context, CGContextGetClipBoundingBox(context), cgImage);
UIImage *preImage = UIGraphicsGetImageFromCurrentImageContext();
//Cleaning up .清理
UIGraphicsEndImageContext();
CGImageRelease(cgImage);
// Rotate the image旋转图像
UIImage *qrImage = [UIImage imageWithCGImage:[preImage CGImage] scale:[preImage scale] orientation:UIImageOrientationDownMirrored];
return qrImage;
}
- (void)viewDidLoad {
[super viewDidLoad];
UIImageView * imageView = [[UIImageView alloc]initWithFrame:CGRectMake(100, 100, 200, 200)];
[self.view addSubview:imageView];
//生成二维码
UIImage *image = [self generateQRCodeFromString:@"nihaome"];
imageView.image = [self image:image scale:10];
/**
* 将图片保存到iPhone本地相册
* UIImage *image 图片对象
* id completionTarget 响应方法对象
* SEL completionSelector 方法
* void *contextInfo
*/
UIImageWriteToSavedPhotosAlbum(imageView.image, self, @selector(image:didFinishSavingWithError:contextInfo:), nil);
}
- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo{
if (error == nil) {
NSLog(@"已存入手机相册");
}else{
NSLog(@"保存失败");
}
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end
2.ZBarSDK扫描二维码
ViewController.m文件
#pragma mark - 扫描按钮
- (IBAction)scanning:(id)sender {
[self Hidekeyboard];
QRViewController *scanner = [[QRViewController alloc] init];
scanner.block = ^(NSString *str){
NSString *beforeDIDStr = _DIDTextField.text;
_DIDTextField.text = str;
};
[self.navigationController pushViewController:scanner animated:YES];
}
QRViewController.m文件
//
// QRViewController.m
//
#import "QRViewController.h"
#import "ZBarSDK.h"
#import "Header.h"
#import <AVFoundation/AVFoundation.h>
@interface QRViewController () <ZBarReaderViewDelegate,ZBarReaderDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate>
{
ZBarReaderView *ReaderView;
UIImageView * scanZomeBack;
UIImageView * readLineView;
BOOL is_Anmotion;
}
// 其他变量
@property (nonatomic,weak) UIActivityIndicatorView *indicator;
@end
@implementation QRViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"<返回" style:UIBarButtonItemStylePlain target:self action:@selector(gotoBack:)];
self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"相册" style:UIBarButtonItemStylePlain target:self action:@selector(xiangceClicked:)];
is_Anmotion = NO;
[self showLoading];
}
-(void)viewWillAppear:(BOOL)animated
{
// 初始化ZBarReaderView
ReaderView =[ZBarReaderView new];
ReaderView.frame = CGRectMake(0, 0, Width, Height);
//设置delegate,使用ZBarReaderView的类要实现 ZBarReaderViewDelegate代理。
ReaderView.readerDelegate =self;
// 不使用Pinch手势变焦
ReaderView.allowsPinchZoom =NO;
ReaderView.showsFPS =NO;
ReaderView.tracksSymbols = NO;
//关闭闪光灯
ReaderView.torchMode = 0;
[self.view addSubview:ReaderView];
//边角
UIImage *hbImage=[UIImage imageNamed:@"twocode_bg"];
scanZomeBack=[[UIImageView alloc] initWithImage:hbImage];
scanZomeBack.clipsToBounds =YES;
CGRect mImagerect;
if (Width==320) {
mImagerect=CGRectMake(60, 150, 200, 200);
}else
{
if (IS_IPHONE_6P) {
mImagerect=CGRectMake(107, 180, 200, 200);
}
else
{
mImagerect=CGRectMake(87, 180, 200, 200);
}
}
[scanZomeBack setFrame:mImagerect];
[ReaderView addSubview:scanZomeBack];
//扫描区域
ReaderView.scanCrop =CGRectMake(0, 0, 1, 1);
// 开始扫描
[ReaderView start];
//扫描动画
[self loopDrawLine];
//我的二维码
UILabel * textLabel =[[UILabel alloc]initWithFrame:CGRectMake(scanZomeBack.frame.origin.x, scanZomeBack.frame.origin.y+scanZomeBack.frame.size.height+10, 200, 25)];
textLabel.text =@"将二维码放入框内,即可自动扫描";
textLabel.font =[UIFont systemFontOfSize:13];
textLabel.textColor =[UIColor whiteColor];
[self.view addSubview:textLabel];
}
#pragma mark -- 二维码扫描动画
#pragma mark 扫描动画
-(void)loopDrawLine
{
CGRect rect = CGRectMake(0, -(scanZomeBack.frame.size.height), (scanZomeBack.frame.size.width), scanZomeBack.frame.size.height);
if (readLineView) {
[readLineView removeFromSuperview];
}
readLineView = [[UIImageView alloc] initWithFrame:rect];
[readLineView setImage:[UIImage imageNamed:@"Qcode_bg"]];
[UIView animateWithDuration:3.0
delay: 0.0
options: UIViewAnimationOptionCurveEaseIn
animations:^{
//修改fream的代码写在这里
readLineView.frame =CGRectMake(0, 0, scanZomeBack.frame.size.width, scanZomeBack.frame.size.height);
[readLineView setAnimationRepeatCount:0];
}
completion:^(BOOL finished){
if (!is_Anmotion) {
NSLog(@"---");
[self loopDrawLine];
}
}];
[scanZomeBack addSubview:readLineView];
}
#pragma mark --二维码回调
- (void)readerView:(ZBarReaderView *)readerView didReadSymbols:(ZBarSymbolSet *)symbols fromImage:(UIImage *)image
{
NSLog(@"%@",symbols);
for (ZBarSymbol *symbol in symbols) {
NSLog(@"%@", symbol.data);
if (_block) {
_block(symbol.data);
}
[ReaderView stop]; // 停止扫描
is_Anmotion = YES;
[self.navigationController popViewControllerAnimated:YES];
}
}
#pragma mark -- 调用相册
-(void)xiangceClicked:(id)sender{
ZBarReaderController *reader = [ZBarReaderController new];
reader.allowsEditing = YES;
reader.readerDelegate = self;
reader.sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;
// 相机是否授权
if ([AVCaptureDevice respondsToSelector:@selector(authorizationStatusForMediaType:)])
{
if (!([AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo] == AVAuthorizationStatusAuthorized))
{
NSLog(@"CaptureDevice not authorized");
}
}
[self presentViewController:reader animated:YES completion:^{
NSLog(@"跳转成功---");
is_Anmotion = YES;
}];
}
#pragma mark -- 进入相册回调
// 当选取原始图片或者视频后,调用该方法
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
id<NSFastEnumeration> results = [info objectForKey: ZBarReaderControllerResults];
if ([info count]>2) {
int quality = 0;
ZBarSymbol *bestResult = nil;
for(ZBarSymbol *sym in results) {
int q = sym.quality;
if(quality < q) {
quality = q;
bestResult = sym;
}
}
[self performSelector: @selector(presentResult:) withObject: bestResult afterDelay: .001];
}else {
ZBarSymbol *symbol = nil;
for(symbol in results)
break;
[self performSelector: @selector(presentResult:) withObject: symbol afterDelay: .001];
}
[picker dismissViewControllerAnimated:YES completion:^{
}];
}
//扫描失败,无法读取二维码信息
- (void) readerControllerDidFailToRead: (ZBarReaderController*) reader
withRetry: (BOOL) retry
{
//retry == YES 选择图片为非二维码
NSLog(@"扫描失败,无法读取二维码信息");
[reader popViewControllerAnimated:YES];
}
//取消选择图片
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
[picker dismissViewControllerAnimated:YES completion:^{
//重新开始扫描动画
is_Anmotion = NO;
}];
}
//相册回调内的触发方法
- (void) presentResult: (ZBarSymbol*)sym {
if (sym) {
if (_block) {
_block(sym.data);
}
[ReaderView stop]; // 停止扫描
is_Anmotion = YES;
[self.navigationController popViewControllerAnimated:YES];
}
}
#pragma mark --返回
-(void)gotoBack:(id)sender
{
[ReaderView stop]; // 停止扫描
is_Anmotion = YES;
[self.navigationController popViewControllerAnimated:YES];
}
// 显示菊花
- (void)showLoading
{
if (!self.indicator)
{
UIActivityIndicatorView *indicator = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
indicator.backgroundColor = [UIColor clearColor];
indicator.center = self.view.center;
indicator.hidden = NO;
self.indicator = indicator;
[self.view addSubview:indicator];
[self.view bringSubviewToFront:indicator];
}
[self.indicator startAnimating];
}
// 隐藏菊花
-(void)hideLoading
{
if (self.indicator && [self.indicator isAnimating]) {
[self.indicator stopAnimating];
}
}
@end