参考:https://github.com/nglszs/BCQRcode

方式一:

#import <UIKit/UIKit.h>
@interface ViewController : UIViewController
@end
**************
#import "ViewController.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
  [super viewDidLoad];
  self.title = @"二维码";
  UIBarButtonItem *leftBtn = [[UIBarButtonItem alloc]
                initWithTitle:@"生成"
                style:UIBarButtonItemStylePlain
                target:self
                action:@selector(backView)];
  self.navigationItem.leftBarButtonItem = leftBtn;
  UIBarButtonItem *rightBtn = [[UIBarButtonItem alloc]
                 initWithTitle:@"扫描"
                 style:UIBarButtonItemStylePlain
                 target:self
                 action:@selector(ScanView)];
  self.navigationItem.rightBarButtonItem = rightBtn;
  //长按识别图中的二维码,类似于微信里面的功能,前提是当前页面必须有二维码
  UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(readCode:)];
  [self.view addGestureRecognizer:longPress];
}
- (void)readCode:(UILongPressGestureRecognizer *)pressSender {
  if (pressSender.state == UIGestureRecognizerStateBegan) {
    //截图 再读取
    UIGraphicsBeginImageContextWithOptions(self.view.bounds.size, YES, 0);
    CGContextRef context = UIGraphicsGetCurrentContext();
    [self.view.layer renderInContext:context];
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
   //识别二维码 
    CIImage *ciImage = [[CIImage alloc] initWithCGImage:image.CGImage options:nil];
    CIContext *ciContext = [CIContext contextWithOptions:@{kCIContextUseSoftwareRenderer : @(YES)}]; // 软件渲染
    CIDetector *detector = [CIDetector detectorOfType:CIDetectorTypeQRCode context:ciContext options:@{CIDetectorAccuracy : CIDetectorAccuracyHigh}];// 二维码识别
    NSArray *features = [detector featuresInImage:ciImage];
    for (CIQRCodeFeature *feature in features) {
      NSLog(@"msg = %@",feature.messageString); // 打印二维码中的信息
      //对结果进行处理
      ResultViewController *resultVC = [[ResultViewController alloc] init];
      resultVC.contentString = feature.messageString;
      [self.navigationController pushViewController:resultVC animated:NO];
    }
  }
}
- (void)backView {
    UIImageView *codeImageView = [[UIImageView alloc] initWithFrame:CGRectMake((BCWidth - 200)/2, 100, 200, 200)];
    codeImageView.layer.borderColor = [UIColor orangeColor].CGColor;
    codeImageView.layer.borderWidth = 1;
    [self.view addSubview:codeImageView];
  //有图片的时候,也可以不设置圆角
  [codeImageView creatCode:@"https://www.baidu.com" Image:[UIImage imageNamed:@"bg"] andImageCorner:4];
  //没有图片的时候
  // [codeImageView creatCode:@"这波可以" Image:nil andImageCorner:4];
}
- (void)ScanView {
  [self.navigationController pushViewController:[ScanCodeViewController new] animated:YES];
}
- (void)didReceiveMemoryWarning {
  [super didReceiveMemoryWarning];
  // Dispose of any resources that can be recreated.
}
@end
************生成二维码
#import <UIKit/UIKit.h>
@interface UIImageView (CreatCode)
/**
 这里传入二维码的信息,image是加载二维码上方的图片,如果不要图片直接codeImage为nil即可,后面是图片的圆角
 */
- (void)creatCode:(NSString *)codeContent Image:(UIImage *)codeImage andImageCorner:(CGFloat)imageCorner;
@end
**************
#import "UIImageView CreatCode.h"
#define ImageSize self.bounds.size.width
@implementation UIImageView (CreatCode)
- (void)creatCode:(NSString *)codeContent Image:(UIImage *)codeImage andImageCorner:(CGFloat)imageCorner {
  //用CoreImage框架实现二维码的生成,下面方法最好异步调用
  dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
    CIFilter *codeFilter = [CIFilter filterWithName:@"CIQRCodeGenerator"];
    //每次调用都恢复其默认属性
    [codeFilter setDefaults];
    NSData *codeData = [codeContent dataUsingEncoding:NSUTF8StringEncoding];
    //设置滤镜数据
    [codeFilter setValue:codeData forKey:@"inputMessage"];
    //获得滤镜输出的图片
    CIImage *outputImage = [codeFilter outputImage];
    //这里的图像必须经过位图转换,不然会很模糊
    UIImage *translateImage = [self creatUIImageFromCIImage:outputImage andSize:ImageSize];
    //这里如果不想设置圆角,直接传一个image就好了
    UIImage *resultImage = [self setSuperImage:translateImage andSubImage:[self imageCornerRadius:imageCorner andImage:codeImage]];
    dispatch_async(dispatch_get_main_queue(), ^{
      self.image = resultImage;
    });
});
}
//这里的size我是用imageview的宽度来算的,你可以改为自己想要的size
- (UIImage *)creatUIImageFromCIImage:(CIImage *)image andSize:(CGFloat)size {
  //下面是创建bitmao没什么好解释的,不懂得自行百度或者参考官方文档
  CGRect extent = CGRectIntegral(image.extent);
  CGFloat scale = MIN(size/CGRectGetWidth(extent), size/CGRectGetHeight(extent));
  size_t width = CGRectGetWidth(extent) * scale;
  size_t height = CGRectGetHeight(extent) * scale;
  CGColorSpaceRef colorRef = CGColorSpaceCreateDeviceGray();
  CGContextRef contextRef = CGBitmapContextCreate(nil, width, height, 8, 0, colorRef, (CGBitmapInfo)kCGImageAlphaNone);
  CIContext *context = [CIContext contextWithOptions:nil];
  CGImageRef imageRef = [context createCGImage:image fromRect:extent];
  CGContextSetInterpolationQuality(contextRef, kCGInterpolationNone);
  CGContextScaleCTM(contextRef, scale, scale);
  CGContextDrawImage(contextRef, extent, imageRef);
  CGImageRef newImage = CGBitmapContextCreateImage(contextRef);
  CGContextRelease(contextRef);
  CGImageRelease(imageRef);
  return [UIImage imageWithCGImage:newImage];
}
//这里将二维码上方的图片设置圆角并缩放
- (UIImage *)imageCornerRadius:(CGFloat)cornerRadius andImage:(UIImage *)image {
  //这里是将图片进行处理,frame不能太大,否则会挡住二维码
  CGRect frame = CGRectMake(0, 0, ImageSize/5, ImageSize/5);
  UIGraphicsBeginImageContextWithOptions(frame.size, NO, 0);
  [[UIBezierPath bezierPathWithRoundedRect:frame cornerRadius:cornerRadius] addClip];
  [image drawInRect:frame];
  UIImage *clipImage = UIGraphicsGetImageFromCurrentImageContext();
  UIGraphicsEndImageContext();
  return clipImage;
}
- (UIImage *)setSuperImage:(UIImage *)superImage andSubImage:(UIImage *)subImage {
  //将两张图片绘制在一起
  UIGraphicsBeginImageContextWithOptions(superImage.size, YES, 0);
  [superImage drawInRect:CGRectMake(0, 0, superImage.size.width, superImage.size.height)];
  [subImage drawInRect:CGRectMake((ImageSize - ImageSize/5)/2, (ImageSize - ImageSize/5)/2, subImage.size.width, subImage.size.height)];
  UIImage *resultImage = UIGraphicsGetImageFromCurrentImageContext();
  UIGraphicsEndImageContext();
  return resultImage;
}
@end
***************扫描二维码
#import <UIKit/UIKit.h>
#import <AVFoundation/AVFoundation.h>
@interface ScanCodeViewController : UIViewController<AVCaptureMetadataOutputObjectsDelegate>
{
  AVCaptureSession * session;
  AVCaptureMetadataOutput * output;
  NSInteger lineNum;
  BOOL upOrDown;
  NSTimer *lineTimer;
}
@property (nonatomic, strong) UIImageView *lineImageView;
@property (nonatomic, strong) UIImageView *backImageView;
@end
******************
#import "ScanCodeViewController.h"
@implementation ScanCodeViewController
- (void)viewDidLoad {
  [super viewDidLoad];
  if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 7.0) {
        AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
        if (authStatus == AVAuthorizationStatusDenied || authStatus == AVAuthorizationStatusRestricted)
        {
          [[[UIAlertView alloc] initWithTitle:nil message:@"本应用无访问相机的权限,如需访问,可在设置中修改" delegate:nil cancelButtonTitle:@"好的" otherButtonTitles:nil, nil] show];
          return;
        } else {
          //打开相机
          AVCaptureDevice * device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
          //创建输入流
          AVCaptureDeviceInput * input = [AVCaptureDeviceInput deviceInputWithDevice:device error:nil];
          //创建输出流
          output = [[AVCaptureMetadataOutput alloc]init];
          //设置代理 在主线程里刷新
          [output setMetadataObjectsDelegate:self queue:dispatch_get_main_queue()];
          //设置扫描区域,这个需要仔细调整
          [output setRectOfInterest:CGRectMake(64/BCHeight, (BCWidth - 320)/2/BCWidth, 320/BCHeight, 320/BCWidth)];
          //初始化链接对象
          session = [[AVCaptureSession alloc]init];
          //高质量采集率
          [session setSessionPreset:AVCaptureSessionPresetHigh];
          [session addInput:input];
          [session addOutput:output];
          //设置扫码支持的编码格式
          output.metadataObjectTypes=@[AVMetadataObjectTypeQRCode,AVMetadataObjectTypeEAN13Code, AVMetadataObjectTypeEAN8Code, AVMetadataObjectTypeCode128Code];
          AVCaptureVideoPreviewLayer * layer = [AVCaptureVideoPreviewLayer layerWithSession:session];
          layer.videoGravity=AVLayerVideoGravityResizeAspectFill;
          layer.frame=self.view.layer.bounds;
          [self.view.layer addSublayer:layer];
      }
  }
        [self _initView];
}
//里面所有的控件可以自己定制,这里只是简单的例子
- (void)_initView {
  //扫码框
  _backImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 64, BCWidth, BCHeight - 64)];
  _backImageView.image = [UIImage imageNamed:@"camera_bg"];
  [self.view addSubview:_backImageView];
  _lineImageView = [[UIImageView alloc] initWithFrame:CGRectMake(16, 15, BCWidth - 32, 1)];
  _lineImageView.backgroundColor = [UIColor orangeColor];
  [_backImageView addSubview:_lineImageView];
  //各种参数设置
  lineNum = 0;
  upOrDown = NO;
  lineTimer = [NSTimer scheduledTimerWithTimeInterval:0.01 target:self selector:@selector(lineAnimation) userInfo:nil repeats:YES];
}
-(void)lineAnimation {
  if (upOrDown == NO) {
    lineNum   ;
    _lineImageView.frame = CGRectMake(CGRectGetMinX(_lineImageView.frame), 15   lineNum, BCWidth - 32, 1);
    CGFloat tempHeight = CGRectGetHeight(_backImageView.frame) * 321/542;
    NSInteger height = (NSInteger)tempHeight   20;
    if (lineNum == height) {
      upOrDown = YES;
    }
  }
  else {
    lineNum --;
    _lineImageView.frame = CGRectMake(CGRectGetMinX(_lineImageView.frame), 15   lineNum, BCWidth - 32, 1);
    if (lineNum == 0) {
      upOrDown = NO;
    }
  }
}
#pragma mark AVCaptureMetadataOutputObjectsDelegate
- (void)captureOutput:(AVCaptureOutput *)captureOutput didOutputMetadataObjects:(NSArray *)metadataObjects fromConnection:(AVCaptureConnection *)connection {
  if ([metadataObjects count] > 0) {
    [session stopRunning]; //停止扫码
    AVMetadataMachineReadableCodeObject *metadataObject = [metadataObjects firstObject];
    ResultViewController *resultVC = [[ResultViewController alloc] init];
    resultVC.contentString = metadataObject.stringValue;
    [self.navigationController pushViewController:resultVC animated:NO];
  }
}
- (void)viewWillAppear:(BOOL)animated {
  [super viewWillAppear:animated];
  [session startRunning];
  [lineTimer setFireDate:[NSDate distantPast]];
}
- (void)viewWillDisappear:(BOOL)animated {
  [super viewWillDisappear:animated];
  [session stopRunning];
  [lineTimer setFireDate:[NSDate distantFuture]];
  if (![self.navigationController.viewControllers containsObject:self]) {//释放timer
    [lineTimer invalidate];
    lineTimer = nil;
  }
}
- (void)dealloc {
  NSLog(@"已释放");
}
@end
*******吧识别的二维码信息传过来加载网页
#import <UIKit/UIKit.h>
@interface ResultViewController : UIViewController
@property(nonatomic, retain)NSString *contentString;
@end
********
#import "ResultViewController.h"
#import <WebKit/WebKit.h>
@implementation ResultViewController
- (void)viewDidLoad {
  [super viewDidLoad];
  //这个界面我只是简单的处理一下,可以自己定制,实际应用中扫码跳转不可能就这两种逻辑
  if ([_contentString hasPrefix:@"http"]) {
    WKWebView *showView = [[WKWebView alloc] initWithFrame:BCScreen];
    NSURLRequest *codeRequest = [NSURLRequest requestWithURL:[NSURL URLWithString:_contentString]];
    [showView loadRequest:codeRequest];
    [self.view addSubview:showView];
  } else {
    UILabel *showLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 80, 200, 50)];
    showLabel.center = self.view.center;
    showLabel.font = [UIFont boldSystemFontOfSize:16];
    showLabel.text = [NSString stringWithFormat:@"扫描结果是---%@",_contentString];
    showLabel.numberOfLines = 0;
    [self.view addSubview:showLabel];
  }
}
@end

方式二:识别网页中的二维码

iOS WebView中 长按二维码的识别

思路:

长按webView 的过程中 截屏,再去解析是否有二维码,但是有个缺点 就是 万一截了一个 一半的二维码 那就无解了。

在webview中 注入获取点击图片的JS 获取图片,再解析。缺点:万一图片过大 需要下载,势必会影响用户体验。

@interface CVWebViewController ()<UIGestureRecognizerDelegate>
@property (weak, nonatomic) IBOutlet UIWebView *webView;
@end
@implementation CVWebViewController
- (void)viewDidLoad
{
  [self.webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://mp.weixin.qq.com/s?__biz=MzI2ODAzODAzMw==&mid=2650057120&idx=2&sn=c875f7d03ea3823e8dcb3dc4d0cff51d&scene=0#wechat_redirect"]]];
  UILongPressGestureRecognizer *longPressed = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longPressed:)];
  longPressed.delegate = self;
  [self.webView addGestureRecognizer:longPressed];
}
- (void)longPressed:(UITapGestureRecognizer*)recognizer
{
  if (recognizer.state != UIGestureRecognizerStateBegan) {
    return;
  }
  CGPoint touchPoint = [recognizer locationInView:self.webView];
  NSString *js = [NSString stringWithFormat:@"document.elementFromPoint(%f, %f).src", touchPoint.x, touchPoint.y];
  NSString *imageUrl = [self.webView stringByEvaluatingJavaScriptFromString:js];
  if (imageUrl.length == 0) {
    return;
  }
  NSLog(@"image url:%@",imageUrl);
  NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:imageUrl]];
  UIImage *image = [UIImage imageWithData:data];
  if (image) {
    //......
    //save image or Extract QR code
  }
}
-(BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer
{
  return YES;
}

以上所述是小编给大家介绍的iOS模仿微信长按识别二维码的多种方式,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对Devmax网站的支持!

iOS模仿微信长按识别二维码的多种方式的更多相关文章

  1. 手对手的教你用canvas画一个简单的海报的方法示例

    企业的广告投入开始从电视等传统媒体向基于圈层文化的新媒体精准营销转移,很多人都想制作一张属于自己的海报,本文介绍了手对手的教你用canvas画一个简单的海报的方法示例,感兴趣的可以了解一下

  2. HTML5在微信内置浏览器下右上角菜单的调整字体导致页面显示错乱的问题

    HTML5在微信内置浏览器下,在右上角菜单的调整字体导致页面显示错乱的问题,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友参考下吧

  3. iOS实现拖拽View跟随手指浮动效果

    这篇文章主要为大家详细介绍了iOS实现拖拽View跟随手指浮动,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

  4. ios – containerURLForSecurityApplicationGroupIdentifier:在iPhone和Watch模拟器上给出不同的结果

    我使用默认的XCode模板创建了一个WatchKit应用程序.我向iOSTarget,WatchkitAppTarget和WatchkitAppExtensionTarget添加了应用程序组权利.(这是应用程序组名称:group.com.lombax.fiveminutes)然后,我尝试使用iOSApp和WatchKitExtension访问共享文件夹URL:延期:iOS应用:但是,测试NSURL

  5. ios – Testflight无法安装应用程序

    我有几个测试人员注册了testflight并连接了他们的设备……他们有不同的ios型号……但是所有这些都有同样的问题.当他们从“safari”或“testflight”应用程序本身单击应用程序的安装按钮时……达到约90%并出现错误消息…

  6. ibm-mobilefirst – 在iOS 7.1上获取“无法安装应用程序,因为证书无效”错误

    当我的客户端将他们的设备更新到iOS7.1,然后尝试从AppCenter更新我们的应用程序时,我收到了上述错误.经过一番搜索,我找到了一个类似问题的帖子here.但是后来因为我在客户端使用AppCenter更新应用程序的环境中,我无法使用USB插件并为他们安装应用程序.在发布支持之前,是否有通过AppCenter进行下载的解决方法?

  7. ios – 视图的简单拖放?

    我正在学习iOS,但我找不到如何向UIView添加拖放行为.我试过了:它说“UIView没有可见的接口声明选择器addTarget”此外,我尝试添加平移手势识别器,但不确定这是否是我需要的它被称为,但不知道如何获得事件的坐标.在iOS中注册移动事件回调/拖放操作的标准简单方法是什么?

  8. ios – 什么控制iTunes中iPhone应用程序支持的语言列表?

    什么控制iPhone应用程序的iTunes页面中支持的语言?

  9. ios – 获得APNs响应BadDeviceToken或Unregistered的可能原因是什么?

    我知道设备令牌在某些时候是有效的.用户如何使其设备令牌变坏?从关于“未注册”的文档:Thedevicetokenisinactiveforthespecifiedtopic.这是否意味着应用程序已被删除?.您应该看到四种分发方法:如果您选择AppStore或Enterprise,您将在后面的对话框中看到Xcode将APNS权利更改为生产:如果选择AdHoc或Development,则aps-environment下的文本将是开发,然后应与后端的配置匹配.

  10. ios – 当我关闭应用程序时,我从调试器获得消息:由于信号15而终止

    我怎么能解决这个问题,我不知道这个链接MypreviousproblemaboutCoredata对我的问题有影响吗?当我cmd应用程序的Q时,将出现此消息.Messagefromdebugger:Terminatedduetosignal15如果谁知道我以前的问题的解决方案,请告诉我.解决方法>来自调试器的消息:每当用户通过CMD-Q(退出)或STOP手动终止应用程序(无论是在iOS模拟器中还是

随机推荐

  1. iOS实现拖拽View跟随手指浮动效果

    这篇文章主要为大家详细介绍了iOS实现拖拽View跟随手指浮动,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

  2. iOS – genstrings:无法连接到输出目录en.lproj

    使用我桌面上的项目文件夹,我启动终端输入:cd然后将我的项目文件夹拖到终端,它给了我路径.然后我将这行代码粘贴到终端中找.-name*.m|xargsgenstrings-oen.lproj我在终端中收到此错误消息:genstrings:无法连接到输出目录en.lproj它多次打印这行,然后说我的项目是一个目录的路径?没有.strings文件.对我做错了什么的想法?

  3. iOS 7 UIButtonBarItem图像没有色调

    如何确保按钮图标采用全局色调?解决方法只是想将其转换为根注释,以便为“回答”复选标记提供更好的上下文,并提供更好的格式.我能想出这个!

  4. ios – 在自定义相机层的AVFoundation中自动对焦和自动曝光

    为AVFoundation定制图层相机创建精确的自动对焦和曝光的最佳方法是什么?

  5. ios – Xcode找不到Alamofire,错误:没有这样的模块’Alamofire’

    我正在尝试按照github(https://github.com/Alamofire/Alamofire#cocoapods)指令将Alamofire包含在我的Swift项目中.我创建了一个新项目,导航到项目目录并运行此命令sudogeminstallcocoapods.然后我面临以下错误:搜索后我设法通过运行此命令安装cocoapodssudogeminstall-n/usr/local/bin

  6. ios – 在没有iPhone6s或更新的情况下测试ARKit

    我在决定下载Xcode9之前.我想玩新的框架–ARKit.我知道要用ARKit运行app我需要一个带有A9芯片或更新版本的设备.不幸的是我有一个较旧的.我的问题是已经下载了新Xcode的人.在我的情况下有可能运行ARKit应用程序吗?那个或其他任何模拟器?任何想法或我将不得不购买新设备?解决方法任何iOS11设备都可以使用ARKit,但是具有高质量AR体验的全球跟踪功能需要使用A9或更高版本处理器的设备.使用iOS11测试版更新您的设备是必要的.

  7. 将iOS应用移植到Android

    我们制作了一个具有2000个目标c类的退出大型iOS应用程序.我想知道有一个最佳实践指南将其移植到Android?此外,由于我们的应用程序大量使用UINavigation和UIView控制器,我想知道在Android上有类似的模型和实现.谢谢到目前为止,guenter解决方法老实说,我认为你正在计划的只是制作难以维护的糟糕代码.我意识到这听起来像很多工作,但从长远来看它会更容易,我只是将应用程序的概念“移植”到android并从头开始编写.

  8. ios – 在Swift中覆盖Objective C类方法

    我是Swift的初学者,我正在尝试在Swift项目中使用JSONModel.我想从JSONModel覆盖方法keyMapper,但我没有找到如何覆盖模型类中的Objective-C类方法.该方法的签名是:我怎样才能做到这一点?解决方法您可以像覆盖实例方法一样执行此操作,但使用class关键字除外:

  9. ios – 在WKWebView中获取链接URL

    我想在WKWebView中获取tapped链接的url.链接采用自定义格式,可触发应用中的某些操作.例如HTTP://我的网站/帮助#深层链接对讲.我这样使用KVO:这在第一次点击链接时效果很好.但是,如果我连续两次点击相同的链接,它将不报告链接点击.是否有解决方法来解决这个问题,以便我可以检测每个点击并获取链接?任何关于这个的指针都会很棒!解决方法像这样更改addobserver在observeValue函数中,您可以获得两个值

  10. ios – 在Swift的UIView中找到UILabel

    我正在尝试在我的UIViewControllers的超级视图中找到我的UILabels.这是我的代码:这是在Objective-C中推荐的方式,但是在Swift中我只得到UIViews和CALayer.我肯定在提供给这个方法的视图中有UILabel.我错过了什么?我的UIViewController中的调用:解决方法使用函数式编程概念可以更轻松地实现这一目标.

返回
顶部