iOS?系統(tǒng)原生二維碼

本文中使用的是系統(tǒng)原生coreimage抚官,實(shí)現(xiàn)功能?二維碼掃描和解析和生成

======================二維碼掃描和解析=============================

@interfaceScanViewController ()?

@property (weak, nonatomic) IBOutletNSLayoutConstraint *topLayoutConstraint;

@property (nonatomic,strong) AVCaptureSession *codeCaptureSession;

@property (nonatomic,strong) AVCaptureVideoPreviewLayer *codeCaptureVideoPreviewLayer;@end

@implementation ScanViewController

#pragma mark - 進(jìn)入相冊- (IBAction)QRCodeFromPickeC:(id)sender {? ? ? ??

UIImagePickerController *imagePC = [[UIImagePickerControlleralloc] init];? ? ? ?

?imagePC.delegate = self;? ? ? ?

?[selfpresentViewController:imagePC animated:YEScompletion:nil];? ? }

#pragma mark - 點(diǎn)擊圖片進(jìn)行解析- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info

{

[picker dismissViewControllerAnimated:YEScompletion:nil];

NSData *data =? UIImageJPEGRepresentation(info[UIImagePickerControllerOriginalImage], 1);

NSLog(@"%@",[selfstringFromCiImage:[CIImageimageWithData:data]]);

[selfaddAlertViewControllerWithMessage:[selfstringFromCiImage:[CIImageimageWithData:data]]];

}

#pragma mark -? 解析圖片

- (NSString *)stringFromCiImage:(CIImage *)ciimage {

NSString *content = @"" ;

if (!ciimage) {

return content;

}

CIDetector *detector = [CIDetectordetectorOfType:CIDetectorTypeQRCode

context:[CIContext contextWithOptions:nil]

options:@{CIDetectorAccuracy:CIDetectorAccuracyHigh}];

NSArray *features = [detector featuresInImage:ciimage];

if (features.count) {

for (CIFeature *feature in features) {

if ([feature isKindOfClass:[CIQRCodeFeatureclass]]) {

content = ((CIQRCodeFeature *)feature).messageString;

break;

}

}

} else {

[selfaddAlertViewControllerWithMessage:@"未正常解析二維碼圖片, 請確保iphone5/5c以上的設(shè)備"];

NSLog(@"未正常解析二維碼圖片, 請確保iphone5/5c以上的設(shè)備");

}

return content;

}

#pragma mark - 提示框

- (void)addAlertViewControllerWithMessage:(NSString *)message

{

UIAlertController *alert = [UIAlertControlleralertControllerWithTitle:@"解析內(nèi)容"? message:[message stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding] preferredStyle:UIAlertControllerStyleAlert];

[alert addAction:[UIAlertActionactionWithTitle:@"朕知道了扬跋!"style:UIAlertActionStyleDefaulthandler:^(UIAlertAction * _Nonnull action) {

[self.codeCaptureSessionstartRunning];

[selfaddAnimationForLine]; // 上下進(jìn)行掃描的線動畫

}]];

[selfpresentViewController:alert animated:YEScompletion:nil];

}

#pragma mark - 二維碼采集對象

- (AVCaptureSession *)codeCaptureSession

{

if (!_codeCaptureSession) {

// 二維碼采集對象

_codeCaptureSession = [[AVCaptureSessionalloc] init];

}

return_codeCaptureSession;

}

#pragma mark - 顯示采集圖像的對象

- (AVCaptureVideoPreviewLayer *)codeCaptureVideoPreviewLayer

{

if (!_codeCaptureVideoPreviewLayer) {

_codeCaptureVideoPreviewLayer? = [AVCaptureVideoPreviewLayerlayerWithSession:self.codeCaptureSession];

_codeCaptureVideoPreviewLayer.bounds = self.view.bounds;

_codeCaptureVideoPreviewLayer.position = self.view.center;

[self.view.layerinsertSublayer:_codeCaptureVideoPreviewLayeratIndex:0];

}

return_codeCaptureVideoPreviewLayer;

}

- (void)viewWillAppear:(BOOL)animated

{

[super viewWillAppear:animated];

#if TARGET_IPHONE_SIMULATOR//模擬器

UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"小提示" message:@"模擬器不能進(jìn)行掃碼" delegate:nil cancelButtonTitle:@"朕知道了!" otherButtonTitles:nil,nil];

[alert show];

#elif TARGET_OS_IPHONE//真機(jī)

NSLog(@"真機(jī)運(yùn)行時(shí)");

#endif

}

#pragma mark - viewDidLoad

- (void)viewDidLoad {

[superviewDidLoad];

// Do any additional setup after loading the view.

// 隱藏返回按鈕的文字

[[UIBarButtonItemappearance] setBackButtonTitlePositionAdjustment:UIOffsetMake(0, -60)

forBarMetrics:UIBarMetricsDefault];

//------------------------------------------------------ 創(chuàng)建輸入流--------------------------------------------------------

// 信息采集設(shè)備

AVCaptureDevice *codeCaptureDevice = [AVCaptureDevicedefaultDeviceWithMediaType:AVMediaTypeVideo];

NSError *error;

AVCaptureDeviceInput *input = [AVCaptureDeviceInputdeviceInputWithDevice:codeCaptureDevice error:&error];

if (error) {

NSLog(@"創(chuàng)建輸入流error:%@",error);

return;

}

// 設(shè)置輸入流

[self.codeCaptureSessionaddInput:input];

//------------------------------------------------------ 創(chuàng)建輸入流--------------------------------------------------

//------------------------------------------------------ 創(chuàng)建輸出流--------------------------------------------------

AVCaptureMetadataOutput *output = [[AVCaptureMetadataOutputalloc] init];

// 設(shè)置輸出流

[self.codeCaptureSessionaddOutput:output];

//設(shè)置輸出流代理凌节,在代理中獲取二維碼的結(jié)果

[output setMetadataObjectsDelegate:selfqueue:dispatch_get_main_queue()];

// 設(shè)置輸出類型

output.metadataObjectTypes = @[AVMetadataObjectTypeUPCECode,

AVMetadataObjectTypeCode39Code,

AVMetadataObjectTypeCode39Mod43Code,

AVMetadataObjectTypeEAN13Code,

AVMetadataObjectTypeEAN8Code,

AVMetadataObjectTypeCode93Code,

AVMetadataObjectTypeCode128Code,

AVMetadataObjectTypePDF417Code,

AVMetadataObjectTypeQRCode,

AVMetadataObjectTypeAztecCode,

AVMetadataObjectTypeInterleaved2of5Code,

AVMetadataObjectTypeITF14Code,

AVMetadataObjectTypeDataMatrixCode];

//? ? [output availableMetadataObjectTypes]; 獲取輸出支持類型

//設(shè)置采樣率钦听,越高識別越精準(zhǔn)洒试,速度越慢

[self.codeCaptureSessionsetSessionPreset:AVCaptureSessionPreset1920x1080];

//------------------------------------------------------ 創(chuàng)建輸出流--------------------------------------------------

// 采集圖像顯示

[selfcodeCaptureVideoPreviewLayer];

// 開始采集

[self.codeCaptureSessionstartRunning];

}

#pragma mark - 輸出流代理方法----采集到數(shù)據(jù)就會調(diào)用該方法

- (void)captureOutput:(AVCaptureOutput *)captureOutput didOutputMetadataObjects:(NSArray *)metadataObjects fromConnection:(AVCaptureConnection *)connection

{

// 獲得二維碼數(shù)據(jù)

AVMetadataMachineReadableCodeObject *codeObject = [metadataObjects lastObject];

//轉(zhuǎn)化為字符串

NSString *resultString = codeObject.stringValue;

if (resultString) {

[self.codeCaptureSessionstopRunning]; // 停止采集二維碼

self.topLayoutConstraint.constant = 10;

[self.codeCaptureVideoPreviewLayerremoveFromSuperlayer];// 刪除預(yù)覽圖層

}

[selfaddAlertViewControllerWithMessage:resultString];

}

- (void)viewDidAppear:(BOOL)animated

{

[super viewDidAppear:animated];

[selfaddAnimationForLine]; // 上下進(jìn)行掃描的線動畫

}

#pragma mark - 上下進(jìn)行掃描的線動畫

- (void)addAnimationForLine

{

self.topLayoutConstraint.constant = 10;

[self.viewlayoutIfNeeded];

[UIViewbeginAnimations:@"LineAnimation"context:nil];

[UIViewsetAnimationDuration:1.0f];

[UIViewsetAnimationRepeatAutoreverses:YES];

[UIViewsetAnimationRepeatCount:INFINITY];

[UIViewsetAnimationCurve:UIViewAnimationCurveEaseInOut];

self.topLayoutConstraint.constant = [UIScreenmainScreen].bounds.size.width-40-40;

[self.viewlayoutIfNeeded];

[UIViewcommitAnimations];

}

======================二維碼掃描和解析=============================

======================二維碼生成=============================

?#pragma mark -? viewDidLoad

- (void)viewDidLoad {

[superviewDidLoad];

// Do any additional setup after loading the view.

[[UIBarButtonItemappearance] setBackButtonTitlePositionAdjustment:UIOffsetMake(0, -60)

forBarMetrics:UIBarMetricsDefault];

self.codeImageView.image = [selfimageBlackToTransparent: [selfcreateNoninterpolatedUIImageFormCIImage:[selfcreateQRForString:@"請輸入要生成二維碼的內(nèi)容"] withSize:CGRectGetWidth(self.codeImageView.frame)] withRed:0.fandGreen:0.fandBlue:0.f];

self.codeImageView.layer.shadowOffset = CGSizeMake(0, 0.5);? // 設(shè)置陰影的偏移量

self.codeImageView.layer.shadowRadius = 1;? // 設(shè)置陰影的半徑

self.codeImageView.layer.shadowColor = [UIColorblackColor].CGColor; // 設(shè)置陰影的顏色為黑色

self.codeImageView.layer.shadowOpacity = 0.3; // 設(shè)置陰影的不透明度

}

#pragma mark - 根據(jù)指定的字符串來生成二維碼的CIImage對象

- (CIImage *)createQRForString:(NSString *)QRString

{

// 獲取支持的二維碼和條碼生成器

NSLog(@"%@",[CIFilterfilterNamesInCategory:kCICategoryGenerator]);

// 實(shí)例化二維碼濾鏡

CIFilter *QRFilter = [CIFilterfilterWithName:@"CIQRCodeGenerator"];

// 恢復(fù)濾鏡的默認(rèn)屬性

[QRFilter setDefaults]; // 可以省略

// 設(shè)置二維碼的內(nèi)容

[QRFilter setValue:[QRString dataUsingEncoding:NSUTF8StringEncoding] forKey:@"inputMessage"];

// 設(shè)置二維碼的糾錯級別

[QRFilter setValue:@"M"forKey:@"inputCorrectionLevel"];

return QRFilter.outputImage;

}

#pragma mark - 根據(jù)指定的CIImage對象來轉(zhuǎn)換成指定大小的UIImage對象

- (UIImage *)createNoninterpolatedUIImageFormCIImage:(CIImage *)image

withSize:(CGFloat)size

{

CGRect extent = CGRectIntegral(image.extent);

CGFloat scale = MIN(size/CGRectGetWidth(extent), size/CGRectGetHeight(extent));

// 創(chuàng)建bitmap

size_t with = CGRectGetWidth(extent)*scale;

size_t height = CGRectGetHeight(extent)*scale;

CGColorSpaceRef cs = CGColorSpaceCreateDeviceGray();

CGContextRef bitmap = CGBitmapContextCreate(nil, with, height, 8, 0, cs, (CGBitmapInfo)kCGImageAlphaNone);

CIContext *context = [CIContextcontextWithOptions:nil];

CGImageRef bitmapImage = [context createCGImage:image fromRect:extent];

CGContextSetInterpolationQuality(bitmap, kCGInterpolationNone);

CGContextScaleCTM(bitmap, scale, scale);

CGContextDrawImage(bitmap, extent, bitmapImage);

// 保存bitmap到圖片

CGImageRef scaledImage = CGBitmapContextCreateImage(bitmap);

CGContextRelease(bitmap);

CGImageRelease(bitmapImage);

return [UIImageimageWithCGImage:scaledImage];

}

#pragma mark - 二維碼顏色填充

void ProviderReleaseData (void *info, const void *data, size_t size){

free((void*)data);

}

- (UIImage*)imageBlackToTransparent:(UIImage*)image withRed:(CGFloat)red andGreen:(CGFloat)green andBlue:(CGFloat)blue{

const int imageWidth = image.size.width;

const int imageHeight = image.size.height;

size_t? ? ? bytesPerRow = imageWidth * 4;

uint32_t* rgbImageBuf = (uint32_t*)malloc(bytesPerRow * imageHeight);

CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();

CGContextRef context = CGBitmapContextCreate(rgbImageBuf, imageWidth, imageHeight, 8, bytesPerRow, colorSpace,

kCGBitmapByteOrder32Little | kCGImageAlphaNoneSkipLast);

CGContextDrawImage(context, CGRectMake(0, 0, imageWidth, imageHeight), image.CGImage);

// 遍歷像素

int pixelNum = imageWidth * imageHeight;

uint32_t* pCurPtr = rgbImageBuf;

for (int i = 0; i

if ((*pCurPtr & 0xFFFFFF00) < 0x99999900)? ? // 將白色變成透明

{

// 改成下面的代碼,會將圖片轉(zhuǎn)成想要的顏色

uint8_t* ptr = (uint8_t*)pCurPtr;

ptr[3] = red; //0~255

ptr[2] = green;

ptr[1] = blue;

}

else

{

uint8_t* ptr = (uint8_t*)pCurPtr;

ptr[0] = 0;

}

}

// 輸出圖片

CGDataProviderRef dataProvider = CGDataProviderCreateWithData(NULL, rgbImageBuf, bytesPerRow * imageHeight, ProviderReleaseData);

CGImageRef imageRef = CGImageCreate(imageWidth, imageHeight, 8, 32, bytesPerRow, colorSpace,

kCGImageAlphaLast | kCGBitmapByteOrder32Little, dataProvider,

NULL, true, kCGRenderingIntentDefault);

CGDataProviderRelease(dataProvider);

UIImage* resultUIImage = [UIImage imageWithCGImage:imageRef];

// 清理空間

CGImageRelease(imageRef);

CGContextRelease(context);

CGColorSpaceRelease(colorSpace);

return resultUIImage;

}

#pragma mark - Navigation

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {

if ([segue.identifierisEqualToString:@"GenerateVCToQRCodeSetVC"]) {

QRCodeSetViewController *QRCodeSetVC = segue.destinationViewController;

[QRCodeSetVC setQRCodeSetBlock:^(CGFloat R, CGFloat G , CGFloat B, NSString *QRCodeContent) {

self.codeImageView.image = [selfimageBlackToTransparent: [selfcreateNoninterpolatedUIImageFormCIImage:[selfcreateQRForString:QRCodeContent] withSize:CGRectGetWidth(self.codeImageView.frame)] withRed:R andGreen:G andBlue:B];

}];

}

}

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末朴上,一起剝皮案震驚了整個濱河市垒棋,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌痪宰,老刑警劉巖叼架,帶你破解...
    沈念sama閱讀 218,204評論 6 506
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異衣撬,居然都是意外死亡乖订,警方通過查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,091評論 3 395
  • 文/潘曉璐 我一進(jìn)店門具练,熙熙樓的掌柜王于貴愁眉苦臉地迎上來乍构,“玉大人,你說我怎么就攤上這事扛点「缯冢” “怎么了?”我有些...
    開封第一講書人閱讀 164,548評論 0 354
  • 文/不壞的土叔 我叫張陵陵究,是天一觀的道長眠饮。 經(jīng)常有香客問我,道長铜邮,這世上最難降的妖魔是什么仪召? 我笑而不...
    開封第一講書人閱讀 58,657評論 1 293
  • 正文 為了忘掉前任,我火速辦了婚禮松蒜,結(jié)果婚禮上返咱,老公的妹妹穿的比我還像新娘。我一直安慰自己牍鞠,他們只是感情好咖摹,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,689評論 6 392
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著难述,像睡著了一般萤晴。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上胁后,一...
    開封第一講書人閱讀 51,554評論 1 305
  • 那天店读,我揣著相機(jī)與錄音,去河邊找鬼攀芯。 笑死屯断,一個胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播殖演,決...
    沈念sama閱讀 40,302評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼氧秘,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了趴久?” 一聲冷哼從身側(cè)響起丸相,我...
    開封第一講書人閱讀 39,216評論 0 276
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎彼棍,沒想到半個月后灭忠,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,661評論 1 314
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡座硕,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,851評論 3 336
  • 正文 我和宋清朗相戀三年弛作,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片华匾。...
    茶點(diǎn)故事閱讀 39,977評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡缆蝉,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出瘦真,到底是詐尸還是另有隱情,我是刑警寧澤黍瞧,帶...
    沈念sama閱讀 35,697評論 5 347
  • 正文 年R本政府宣布诸尽,位于F島的核電站,受9級特大地震影響印颤,放射性物質(zhì)發(fā)生泄漏您机。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,306評論 3 330
  • 文/蒙蒙 一年局、第九天 我趴在偏房一處隱蔽的房頂上張望际看。 院中可真熱鬧,春花似錦矢否、人聲如沸仲闽。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,898評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽赖欣。三九已至,卻和暖如春验庙,著一層夾襖步出監(jiān)牢的瞬間顶吮,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 33,019評論 1 270
  • 我被黑心中介騙來泰國打工粪薛, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留悴了,地道東北人。 一個月前我還...
    沈念sama閱讀 48,138評論 3 370
  • 正文 我出身青樓,卻偏偏與公主長得像湃交,于是被迫代替她去往敵國和親熟空。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,927評論 2 355

推薦閱讀更多精彩內(nèi)容