The generation and scanning of iOS QR code

Source: Internet
Author: User

Because of the recent work encountered a demand: some fixed fields need to be transferred to each other on multiple mobile side, so I think of the two-dimensional code this magical stuff! Now on the street, even a pancake of the aunt have their own QR code to allow everyone to scan the code to pay. Can see the current QR code usage is high, not only that, in a lot of social apps basically have a sweep with friends this function, so decided to learn this magical thing.

Find some information blog Ah, found that before iOS7 for developers familiar with the third-party QRCode library is:


      • ZXing
        Google produce and open source until now, there are still dedicated maintenance is the world's most widely used QR code library The more stable migration version of iOS is Zxingobj

      • Zbar
        Functionally and zxing, unfortunately, the project will not be maintained after 2012 years, although the code can now be used

But after iOS7, the system framework has been integrated with the generation and reading of QR codes, which makes development much more convenient and more efficient than a third party. Today, let's talk about the generation and scanning of two-dimensional code using the system's native way.

(i) HD QR code

System QR code mainly through the Cifilter object to complete, of course, first we need to import the framework of this class, and implement the following code

#import <CoreImage/CoreImage.h>      //1. Create a filter-Apple does not define this character as a constant     cifilter *filter = [Cifilter filterwithname : @ "Ciqrcodegenerator"];            2. Filter restore default settings      [filter setdefaults];          3. Add data to the filter (regular expression/account number and password)--set filter by KVC, only set NSData type     nsstring *datastring = @ "http://www.baidu.com";     NSData *data = [datastring datausingencoding:nsutf8stringencoding];     [Filter Setvalue:data forkeypath:@ "InputMessage"];          4. Obtain the output of the QR code     ciimage *outputimage = [Filter outputimage];          5. Display two-dimensional code     UIImage *image = [UIImage imagewithciimage:outputimage];

  


通过上面这种最简单的方式 生成的二维码很模糊,而且二维码的大小也不方便控制,

对于我们来说,需求的是一张 能控制大小,并且高清显示的二维码,因此我们需要用一种方式 将CIImage 转为我们心目中那个UIImage
/** generates UIImage */+ (UIImage *) Createnoninterpolateduiimageformciimage of the specified size according to Ciimage: (Ciimage *) image withsize: (    CGFloat) Size {cgrect extent = cgrectintegral (image.extent);        CGFloat scale = MIN (Size/cgrectgetwidth (extent), size/cgrectgetheight (extent));    1. Create bitmap;    size_t width = cgrectgetwidth (extent) * scale;    size_t height = cgrectgetheight (extent) * scale;    Cgcolorspaceref cs = Cgcolorspacecreatedevicegray ();    Cgcontextref bitmapref = cgbitmapcontextcreate (nil, width, height, 8, 0, CS, (Cgbitmapinfo) kcgimagealphanone);    Cicontext *context = [Cicontext Contextwithoptions:nil];    Cgimageref bitmapImage = [context createcgimage:image fromrect:extent];    Cgcontextsetinterpolationquality (Bitmapref, Kcginterpolationnone);    CGCONTEXTSCALECTM (bitmapref, scale, scale);        Cgcontextdrawimage (Bitmapref, extent, bitmapImage);    2. Save bitmap to picture cgimageref Scaledimage = Cgbitmapcontextcreateimage (bitmapref);    Cgcontextrelease (BITMAPREF); Cgimagerelease (bItmapimage); return [UIImage imagewithcgimage:scaledimage];}

( 二 )彩色二维码

In the use of the process found a problem, that is, when we use a long length of the field to generate high-definition QR code, the two-dimensional code will become very dense, thick, when using a mobile phone to scan, because the camera pixel problem is difficult to read the QR code, so I need a color QR code to increase its recognition.

    1. Create Filter Object Cifilter *filter = [Cifilter filterwithname:@ "Ciqrcodegenerator"];        Restore the default properties of the filter [filter setdefaults];    2, set the data nsstring *string_data =; Convert the string to NSData (although the QR code is essentially a string, but here it needs to be converted, not converted to crash) nsdata *qrimagedata = [String_data datausingencoding:nsutf8stringenc        Oding];        Set the input value of the filter, KVC assignment [filter setvalue:qrimagedata forkey:@ "InputMessage"];        3, obtain the filter output image ciimage *outputimage = [Filter outputimage];            Picture is less than (27,27), we need to enlarge outputimage = [Outputimage Imagebyapplyingtransform:cgaffinetransformmakescale (9, 9)];        4, create color filter (color of the use of not much) cifilter * Color_filter = [Cifilter filterwithname:@ "Cifalsecolor"];        Set default value [Color_filter SetDefaults];        5, KVC to the private property assigned value [Color_filter setvalue:outputimage forkey:@ "Inputimage"]; 6, need to use Cicolor for background color and main color paint//inputColor0: Background color, inputColor1 main color//note Do not use [Cicolor redcolor][cicolor Bluecolor ], these uicolor-like methods are available only on iOS 10 systems [Color_filter Setvalue:[cicolor colorwithred:1 green:1 blue:1] forkey:@ "InputColor0"];        [Color_filter setvalue:[cicolor colorwithred:0 green:0 blue:1] forkey:@ "InputColor1"];    7, set output ciimage *colorimage = [Color_filter outputimage]; 8, output UIImage UIImage *image = [UIImage imagewithciiimage:colorimage];

  

Scan two-dimensional code

The main use of scanning is avfoundation is also very simple to use, through the settings <avcapturemetadataoutputobjectsdelegate> The agent can listen for information in the scanned QR code

#import "ViewController.h" #import <AVFoundation/AVFoundation.h> @interface Viewcontroller () < avcapturemetadataoutputobjectsdelegate>///Session Object @property (Nonatomic, strong) Avcapturesession *session;/// Layer Class @property (nonatomic, strong) Avcapturevideopreviewlayer *previewlayer; @end @implementation ViewController-(void) viewdidload {[Super viewdidload];} -(void) Touchesbegan: (Nsset *) touches withevent: (uievent *) event{//1, acquiring camera equipment avcapturedevice *device = [Avcapturedevic        e Defaultdevicewithmediatype:avmediatypevideo];        2. Create input stream Avcapturedeviceinput *input = [Avcapturedeviceinput deviceinputwithdevice:device error:nil];        3. Create output stream Avcapturemetadataoutput *output = [[Avcapturemetadataoutput alloc] init];        4, set agent in the main thread refresh [output Setmetadataobjectsdelegate:self queue:dispatch_get_main_queue ()]; Set the scan range (each value 0~1 to the upper right corner of the screen as the origin of the coordinates)//Note: The scanning range of the QR code is the entire screen, there is no processing (can not be set) Output.rectofinterest = CGRectMake (0.05, 0.2, 0.7        , 0.6); 5, the initialization of the chainObject (Session object) self.session = [[Avcapturesession alloc] init];        High quality acquisition rate [_session Setsessionpreset:avcapturesessionpresethigh];        5.1 Add session input [_session addinput:input];        5.2 Adding session output [_session Addoutput:output]; 6, set the output data type, need to add the meta-data output to the session, before you can specify the metadata type, otherwise error//Set the code format supported by the scan Code (barcode and QR code compatible) Output.metadataobjecttypes = @[avmetadata        Objecttypeqrcode, Avmetadataobjecttypeean13code, Avmetadataobjecttypeean8code, Avmetadataobjecttypecode128code];    7. Instantiate the preview layer and pass _session to tell the layer what to display in the future Self.previewlayer = [Avcapturevideopreviewlayer layerwithsession:_session];    _previewlayer.videogravity = Avlayervideogravityresizeaspectfill;        _previewlayer.frame = Self.view.layer.bounds;        8. Insert the layer into the current view [Self.view.layer Insertsublayer:_previewlayer atindex:0]; 9. Start the session [_session startrunning];} #pragma mark-Get scan results-(void) Captureoutput: (Avcaptureoutput *) captureoutput didoutputmetadataobjects: (Nsarray *) Metadataobjects fromconnection: (AVCAPtureconnection *) connection{if (Metadataobjects.count > 0) {avmetadatamachinereadablecodeobject *object =        [Metadataobjects Lastobject];    NSLog (@ "%@", Object.stringvalue); }} @end

Avcapturemetadataoutput the value of a property has a rectOfInterest 他是用来控制你屏幕扫描的范围的,默认是按照整个屏幕来扫描, rectOfInterest range of 0-1 is a proportional value instead of the actual size but it is also very simple as long as the conversion is good, the only thing to note here is Rectofinterest are calculated on a horizontal screen, so when the vertical screen is in the x-axis and y-axis, you have to swap.

Read QR code

Reads are mainly used in coreimage . However, it is important to emphasize that the function of reading the QR code is only supported after iOS8, and the code read is very simple .

First get  the picture we need to read uiimage * srcimage = qrcodeimage; Cicontext *context = [Cicontext Contextwithoptions:nil]; Cidetector (Cidetector can be used for face recognition) for image parsing, declaring a cidetector, and setting the recognition type cidetectortypeqrcodecidetector *detector = [ Cidetector Detectoroftype:cidetectortypeqrcode context:context options:@{cidetectoraccuracy: Cidetectoraccuracyhigh}]; Ciimage *image = [Ciimage imageWithCGImage:srcImage.CGImage];    The obtained recognition result is the array    nsarray *features = [Detector featuresinimage:[ciimage imagewithcgimage:image. Cgimage]];    for (int index = 0; index < [features count]; index + +) {        ciqrcodefeature *feature = [Features Objectatindex:index] ;        This string is the information we get from the QR code        nsstring *scannedresult = feature.messagestring;}

  

The generation and scanning of iOS QR code

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.