//生成二维码
- (void)aaa
{
//1.创建滤镜
CIFilter *filter = [CIFilter filterWithName:@"CIQRCodeGenerator"];
//2.恢复默认
[filter setDefaults];
//3.给滤镜添加数据
NSString *dataString = @"http://baidu.com";
// NSString *dataString = @"世俗孤岛";
//将数据转换成NSData类型
// UIImage *imageData = [UIImage imageNamed:@"saomiaoxian@3x"];
// NSData * data = UIImageJPEGRepresentation(imageData, 1);
NSData *data = [dataString dataUsingEncoding:NSUTF8StringEncoding];
//通过KVC设置滤镜的二维码输入信息
[filter setValue:data forKey:@"inputMessage"];
//4.获取输出的二维码图片(CIImage类型)
CIImage *outImage = [filter outputImage];
//将CIImage类型的图片装换成UIImage类型的图片
UIImage *image = [UIImage imageWithCIImage:outImage];
//5.显示二维码图片
self.imageView.image = image;
}
//扫描二维码
//首先我自己封装了几个类 QRItem QRMenu QRView,然后在QRViewController 中去实现扫描二维码的功能
#import <UIKit/UIKit.h>
typedef NS_ENUM(NSUInteger, QRItemType) {
QRItemTypeQRCode,
QRItemTypeOther,
};
@interface QRItem : UIButton
@property (nonatomic, assign) QRItemType type;
- (instancetype)initWithFrame:(CGRect)frame
titile:(NSString *)titile;
@end
#import "QRItem.h"
#import <objc/runtime.h>
@implementation QRItem
- (instancetype)initWithFrame:(CGRect)frame
titile:(NSString *)titile{
self = [QRItem buttonWithType:UIButtonTypeSystem];
if (self) {
[self setTitle:titile forState:UIControlStateNormal];
self.frame = frame;
}
return self;
}
@end
#import <UIKit/UIKit.h>
#import "QRItem.h"
typedef void(^QRMenuDidSelectedBlock)(QRItem *item);
@interface QRMenu : UIView
@property (nonatomic, copy) QRMenuDidSelectedBlock didSelectedBlock;
- (instancetype)initWithFrame:(CGRect)frame;
@end
#import "QRMenu.h"
@implementation QRMenu
/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
// Drawing code
}
*/
- (instancetype)initWithFrame:(CGRect)frame {
self = [super initWithFrame:frame];
if (self) {
[self setupQRItem];
}
return self;
}
- (void)setupQRItem {
QRItem *qrItem = [[QRItem alloc] initWithFrame:(CGRect){
.origin.x = 0,
.origin.y = 0,
.size.width = self.bounds.size.width / 2,
.size.height = self.bounds.size.height
} titile:@"二维码扫描"];
qrItem.type = QRItemTypeQRCode;
[self addSubview:qrItem];
QRItem *otherItem = [[QRItem alloc] initWithFrame: (CGRect){
.origin.x = self.bounds.size.width / 2,
.origin.y = 0,
.size.width = self.bounds.size.width / 2,
.size.height = self.bounds.size.height
} titile:@"条形码扫描"];
otherItem.type = QRItemTypeOther;
[self addSubview:otherItem];
[qrItem addTarget:self action:@selector(qrScan:) forControlEvents:UIControlEventTouchUpInside];
[otherItem addTarget:self action:@selector(qrScan:) forControlEvents:UIControlEventTouchUpInside];
}
#pragma mark - Action
- (void)qrScan:(QRItem *)qrItem {
if (self.didSelectedBlock) {
self.didSelectedBlock(qrItem);
}
}
@end
#import <UIKit/UIKit.h>
#import "QRMenu.h"
@protocol QRViewDelegate <NSObject>
-(void)scanTypeConfig:(QRItem *)item;
@end
@interface QRView : UIView
@property (nonatomic, weak) id<QRViewDelegate> delegate;
/**
* 透明的区域
*/
@property (nonatomic, assign) CGSize transparentArea;
@end
#import "QRView.h"
static NSTimeInterval kQrLineanimateDuration = 0.02;
@implementation QRView
{
UIImageView *qrLine;
CGFloat qrLineY;
QRMenu *qrMenu;
}
- (instancetype)initWithFrame:(CGRect)frame {
self = [super initWithFrame:frame];
if (self) {
}
return self;
}
- (void)layoutSubviews {
[super layoutSubviews];
if (!qrLine) {
[self initQRLine];
NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:kQrLineanimateDuration target:self selector:@selector(show) userInfo:nil repeats:YES];
[timer fire];
}
if (!qrMenu) {
[self initQrMenu];
}
}
#pragma mark - 扫描二维码框中的移动的细线
- (void)initQRLine {
qrLine = [[UIImageView alloc] initWithFrame:CGRectMake((self.bounds.size.width - self.transparentArea.width)/2, (self.bounds.size.height - self.transparentArea.height)/2, 439/2, 3/2)];
NSLog(@"self.transparentArea : %f",self.transparentArea.height);
qrLine.image = [UIImage imageNamed:@"saomiaoxian"];
//qrLine.backgroundColor = [UIColor yellowColor];
qrLine.contentMode = UIViewContentModeScaleAspectFill;
[self addSubview:qrLine];
qrLineY = qrLine.frame.origin.y;
}
- (void)initQrMenu {
// 下面灰色视图《二维码 和 条形码 的选择》
CGFloat height = 100;
CGFloat width = self.bounds.size.width;
qrMenu = [[QRMenu alloc] initWithFrame:CGRectMake(0, self.bounds.size.height - height, width, height)];
qrMenu.backgroundColor = [UIColor orangeColor];
[self addSubview:qrMenu];
__weak typeof(self)weakSelf = self;
qrMenu.didSelectedBlock = ^(QRItem *item){
NSLog(@"点击的是%lu",(unsigned long)item.type);
if ([weakSelf.delegate respondsToSelector:@selector(scanTypeConfig:)] ) {
[weakSelf.delegate scanTypeConfig:item];
}
};
}
- (void)show {
[UIView animateWithDuration:kQrLineanimateDuration animations:^{
CGRect rect = qrLine.frame;
rect.origin.y = qrLineY;
qrLine.frame = rect;
} completion:^(BOOL finished) {
CGFloat maxBorder = self.frame.size.height / 2 + self.transparentArea.height / 2 - 4;
if (qrLineY > maxBorder) {
qrLineY = self.frame.size.height / 2 - self.transparentArea.height /2;
}
qrLineY++;
}];
}
- (void)drawRect:(CGRect)rect {
//整个二维码扫描界面的颜色
CGSize screenSize =[UIScreen mainScreen].bounds.size;
CGRect screenDrawRect =CGRectMake(0, 0, screenSize.width,screenSize.height);
//中间清空的矩形框
CGRect clearDrawRect = CGRectMake(screenDrawRect.size.width / 2 - self.transparentArea.width / 2,
screenDrawRect.size.height / 2 - self.transparentArea.height / 2,
self.transparentArea.width,self.transparentArea.height);
CGContextRef ctx = UIGraphicsGetCurrentContext();
[self addScreenFillRect:ctx rect:screenDrawRect];
[self addCenterClearRect:ctx rect:clearDrawRect];
[self addWhiteRect:ctx rect:clearDrawRect];
[self addCornerLineWithContext:ctx rect:clearDrawRect];
}
- (void)addScreenFillRect:(CGContextRef)ctx rect:(CGRect)rect {
CGContextSetRGBFillColor(ctx, 40 / 255.0,40 / 255.0,40 / 255.0,0.5);
CGContextFillRect(ctx, rect); //draw the transparent layer
}
- (void)addCenterClearRect :(CGContextRef)ctx rect:(CGRect)rect {
CGContextClearRect(ctx, rect); //clear the center rect of the layer
}
- (void)addWhiteRect:(CGContextRef)ctx rect:(CGRect)rect {
CGContextStrokeRect(ctx, rect);
CGContextSetRGBStrokeColor(ctx, 1, 1, 1, 1);
CGContextSetLineWidth(ctx, 0.8);
CGContextAddRect(ctx, rect);
CGContextStrokePath(ctx);
}
- (void)addCornerLineWithContext:(CGContextRef)ctx rect:(CGRect)rect{
//画四个边角
CGContextSetLineWidth(ctx, 2);
CGContextSetRGBStrokeColor(ctx, 83 /255.0, 239/255.0, 111/255.0, 1);//绿色
//左上角
CGPoint poinsTopLeftA[] = {
CGPointMake(rect.origin.x+0.7, rect.origin.y),
CGPointMake(rect.origin.x+0.7 , rect.origin.y + 15)
};
CGPoint poinsTopLeftB[] = {CGPointMake(rect.origin.x, rect.origin.y +0.7),CGPointMake(rect.origin.x + 15, rect.origin.y+0.7)};
[self addLine:poinsTopLeftA pointB:poinsTopLeftB ctx:ctx];
//左下角
CGPoint poinsBottomLeftA[] = {CGPointMake(rect.origin.x+ 0.7, rect.origin.y + rect.size.height - 15),CGPointMake(rect.origin.x +0.7,rect.origin.y + rect.size.height)};
CGPoint poinsBottomLeftB[] = {CGPointMake(rect.origin.x , rect.origin.y + rect.size.height - 0.7) ,CGPointMake(rect.origin.x+0.7 +15, rect.origin.y + rect.size.height - 0.7)};
[self addLine:poinsBottomLeftA pointB:poinsBottomLeftB ctx:ctx];
//右上角
CGPoint poinsTopRightA[] = {CGPointMake(rect.origin.x+ rect.size.width - 15, rect.origin.y+0.7),CGPointMake(rect.origin.x + rect.size.width,rect.origin.y +0.7 )};
CGPoint poinsTopRightB[] = {CGPointMake(rect.origin.x+ rect.size.width-0.7, rect.origin.y),CGPointMake(rect.origin.x + rect.size.width-0.7,rect.origin.y + 15 +0.7 )};
[self addLine:poinsTopRightA pointB:poinsTopRightB ctx:ctx];
CGPoint poinsBottomRightA[] = {CGPointMake(rect.origin.x+ rect.size.width -0.7 , rect.origin.y+rect.size.height+ -15),CGPointMake(rect.origin.x-0.7 + rect.size.width,rect.origin.y +rect.size.height )};
CGPoint poinsBottomRightB[] = {CGPointMake(rect.origin.x+ rect.size.width - 15 , rect.origin.y + rect.size.height-0.7),CGPointMake(rect.origin.x + rect.size.width,rect.origin.y + rect.size.height - 0.7 )};
[self addLine:poinsBottomRightA pointB:poinsBottomRightB ctx:ctx];
CGContextStrokePath(ctx);
// UILabel *label = [ControlManager createLabelWithText:@"请打开此网址:write.yeeaoo.com\n扫描二维码,去网页上写作文" frame:CGRectMake(rect.origin.x+0.7, rect.origin.y + rect.size.height - 15+20, KScreen_Width-(rect.origin.x+0.7)*2, 60) textFont:[UIFont systemFontOfSize:15] textColor:[UIColor whiteColor]];
UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(rect.origin.x+0.7, rect.origin.y + rect.size.height - 15+20, 320-(rect.origin.x+0.7)*2, 60) ];
label.text = @"这是一个测试";
label.textColor = [UIColor whiteColor];
label.textAlignment = NSTextAlignmentCenter;
label.numberOfLines = 0;
[self addSubview:label];
}
- (void)addLine:(CGPoint[])pointA pointB:(CGPoint[])pointB ctx:(CGContextRef)ctx {
CGContextAddLines(ctx, pointA, 2);
CGContextAddLines(ctx, pointB, 2);
}
//------------------------------------
#import "QRViewController.h"
#import <AVFoundation/AVFoundation.h>
#import "QRView.h"
@interface QRViewController ()<AVCaptureMetadataOutputObjectsDelegate,QRViewDelegate>
//是展示如何使用 AVFoundation 来进行二维码扫描,更主要的是限制扫描二维码的范围。(因为默认的是全屏扫描)
//苹果原生的扫描。
@property (strong, nonatomic) AVCaptureDevice * device;//代表抽象的硬件设备
@property (strong, nonatomic) AVCaptureDeviceInput * input;//代表输入设备(可以是它的子类),它配置抽象硬件设备的ports
@property (strong, nonatomic) AVCaptureMetadataOutput * output;//它代表输出数据,管理着输出到一个movie或者图像
@property (strong, nonatomic) AVCaptureSession * session;//它是input和output的桥梁。它协调着intput到output的数据传输
@property (strong, nonatomic) AVCaptureVideoPreviewLayer * preview;
@end
@implementation QRViewController
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view.
self.title = @"扫一扫";
/*
有很多Device的input,也有很多数据类型的Output,都通过一个Capture Session来控制进行传输。也即:CaptureDevice适配AVCaptureInput,通过Session来输入到AVCaptureOutput中。这样也就达到了从设备到文件等持久化传输的目的(如从相机设备采集图像到UIImage中)。
*/
_device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
// Input
_input = [AVCaptureDeviceInput deviceInputWithDevice:self.device error:nil];
// Output
_output = [[AVCaptureMetadataOutput alloc]init];
[_output setMetadataObjectsDelegate:self queue:dispatch_get_main_queue()];
// Session
_session = [[AVCaptureSession alloc]init];
[_session setSessionPreset:AVCaptureSessionPresetHigh];
if ([_session canAddInput:self.input])
{
[_session addInput:self.input];
}
if ([_session canAddOutput:self.output])
{
[_session addOutput:self.output];
}
// 条码类型 AVMetadataObjectTypeQRCode
_output.metadataObjectTypes =@[AVMetadataObjectTypeQRCode];
//增加条形码扫描
// _output.metadataObjectTypes = @[AVMetadataObjectTypeEAN13Code,
// AVMetadataObjectTypeEAN8Code,
// AVMetadataObjectTypeCode128Code,
// AVMetadataObjectTypeQRCode];
// Preview
_preview =[AVCaptureVideoPreviewLayer layerWithSession:_session];
_preview.videoGravity =AVLayerVideoGravityResize;
_preview.frame =self.view.layer.bounds;
[self.view.layer insertSublayer:_preview atIndex:0];
// Start
[_session startRunning];
#pragma mark - 二维码还中心的那个小方块,
CGRect screenRect = [UIScreen mainScreen].bounds;
QRView *qrRectView = [[QRView alloc] initWithFrame:screenRect];
qrRectView.transparentArea = CGSizeMake(220, 220);
qrRectView.backgroundColor = [UIColor clearColor];
qrRectView.center = CGPointMake(self.view.frame.size.width / 2, self.view.frame.size.height / 2);
qrRectView.delegate = self;
[self.view addSubview:qrRectView];
UIButton *pop = [UIButton buttonWithType:UIButtonTypeCustom];
pop.frame = CGRectMake(20, 20, 50, 50);
[pop setTitle:@"返回" forState:UIControlStateNormal];
[pop addTarget:self action:@selector(pop:) forControlEvents:UIControlEventTouchUpInside];
//[self.view addSubview:pop];
//修正扫描区域
CGFloat screenHeight = self.view.frame.size.height;
CGFloat screenWidth = self.view.frame.size.width;
CGRect cropRect = CGRectMake((screenWidth - qrRectView.transparentArea.width) / 2,
(screenHeight - qrRectView.transparentArea.height) / 2,
qrRectView.transparentArea.width,
qrRectView.transparentArea.height);
//设置每一帧画面感兴趣的区域(字面意思),那岂不是就是设置扫描范围喽,大喜
//区域的原点在左上方(后面才知道坑苦我了!),然后区域是相对于设备的大小的,默认值是 CGRectMake(0, 0, 1, 1) ,这时候我才知道是有比例关系的,最大值才是1,也就是说只要除以相应的设备宽和高的大小不就行了?然后就改成
[_output setRectOfInterest:CGRectMake(cropRect.origin.y / screenHeight,
cropRect.origin.x / screenWidth,
cropRect.size.height / screenHeight,
cropRect.size.width / screenWidth)];
self.view.backgroundColor = [UIColor orangeColor];
}
- (void)pop:(UIButton *)button {
[self.navigationController popViewControllerAnimated:YES];
}
#pragma mark QRViewDelegate<切换到 条形码 扫描>
-(void)scanTypeConfig:(QRItem *)item {
if (item.type == QRItemTypeQRCode) {
_output.metadataObjectTypes =@[AVMetadataObjectTypeQRCode];
} else if (item.type == QRItemTypeOther) {
_output.metadataObjectTypes = @[AVMetadataObjectTypeEAN13Code,
AVMetadataObjectTypeEAN8Code,
AVMetadataObjectTypeCode128Code,
AVMetadataObjectTypeQRCode];
}
}
#pragma mark AVCaptureMetadataOutputObjectsDelegate <扫描结束后返回的结构>
- (void)captureOutput:(AVCaptureOutput *)captureOutput didOutputMetadataObjects:(NSArray *)metadataObjects fromConnection:(AVCaptureConnection *)connection
{
NSString *stringValue;
if ([metadataObjects count] >0)
{
//停止扫描
[_session stopRunning];
AVMetadataMachineReadableCodeObject * metadataObject = [metadataObjects objectAtIndex:0];
stringValue = metadataObject.stringValue;
//扫描结果
_stringValue = stringValue;
// [self gotoWebWrite];
}
#pragma mark - 扫描结构
NSLog(@"stringValue: %@",stringValue);
if (self.qrUrlBlock) {
self.qrUrlBlock(stringValue);
}
self.myBlock(stringValue);
[self pop:nil];
}
//- (void)gotoWebWrite
//{
if ([self.recordid intValue] == 0) {
NSMutableDictionary *params = [NSMutableDictionary dictionary];
[params setObject:self.note forKey:@"note"];
[params setObject:self.content forKey:@"writing"];
[params setObject:self.resid forKey:@"resid"];
[self loadDataByAction:@"saverecwrite" withParams:params];
}else{
// [self saomiaoLoadToWebWrite];
//
//
// // }
//
//
//}
//
//- (void)saomiaoLoadToWebWrite
//{
NSRange range = [_stringValue rangeOfString:@"="];
NSString *websid = [_stringValue substringFromIndex:range.location + 1];
NSString * randstr = [self random32Char];
[self loadUser];
NSString *hash = [[NSString stringWithFormat:@"%@%@%@",[self.member valueForKey:@"mid"],[self.member valueForKey:@"sid"],randstr] companyMD5];
NSLog(@"hash : %@",[NSString stringWithFormat:@"%@%@%@",[self.member valueForKey:@"mid"],[self.member valueForKey:@"sid"],randstr]);
NSMutableDictionary *params = [NSMutableDictionary dictionary];
[params setObject:randstr forKey:@"sync_randkey"];
[params setObject:hash forKey:@"sync_hashkey"];
[params setObject:@"0" forKey:@"step"];
[params setObject:websid forKey:@"websid"];
[params setObject:self.resid forKey:@"resid"];
[params setObject:@"1223" forKey:@"recordid"];
[params setObject:@"writingtest" forKey:@"willgo"];
[self loadDataByAction:@"qrcode" withParams:params];
//
//
//}
//
//- (void)requestSuccessed:(NSDictionary *)json
//{
// NSLog(@"json : %@",json);
// int ret = [[json valueForKey:@"ret"] intValue];
// NSString *action = [[json valueForKey:@"retinfo"] valueForKey:@"action"];
//
// if (ret == 1) {
//
// if ([action isEqualToString:@"qrcode"]) {
//
// // [self showAlertView:@"扫描完成"];
//
// //[self pop:nil];
// }
//
// if ([action isEqualToString:@"saverecwrite"]) {
//
// self.recordid = [[json valueForKey:@"retinfo"] valueForKey:@"recordid"];
// [self saomiaoLoadToWebWrite];
//
// }
// }else{
//
// //[self showAlertView:[[json valueForKey:@"retinfo"] valueForKey:@"errormsg"]];
// if ([action isEqualToString:@"qrcode"]) {
//
// // [self showAlertView:@"扫描失败"];
// }
// }
//
//
//}
//
- (void)loadToWeb
{
//
}
-(void)viewDidAppear:(BOOL)animated
{
}
-(void)viewDidDisappear:(BOOL)animated
{
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
-(void) viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
// self.navigationController.navigationBar.hidden = YES;
// if([self getNewTestedFlag] == 1)
// {
// //[self loadData];
// }
}
- (void)viewWillDisappear:(BOOL)animated
{
self.navigationController.navigationBar.hidden = NO;
}
/*
#pragma mark - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
// Get the new view controller using [segue destinationViewController].
// Pass the selected object to the new view controller.
}
*/