Swift avfoundation QR code scanning and generation

Source: Internet
Author: User

Project ultimately need not support iOS6 (tear), in the QR code scanning this piece, can completely abandon the ZXing library, instead of the system AVFoundation , took a swift demo, the effect such as the following:
GitHub Address: point here

Related AVFoundation and Core Image (filters, etc.), you can first look at the Objc.io of the 21st and 23rd phases of the introduction.

Initializing video Capture
 // 初始化视频捕获 private func initCapture() { // 代表抽象的硬件设备,这里传入video let captureDevice = AVCaptureDevice.defaultDeviceWithMediaType(AVMediaTypeVideo) var error: NSError?

// 输入流 var captureInput = AVCaptureDeviceInput.deviceInputWithDevice(captureDevice, error: &error) as?

Avcapturedeviceinput if (Error! = Nil && Captureinput = = nil) {Let Erroralert = Uialertcontroll ER (title:"Reminders", Message:"in the iphone's \" Settings-privacy-camera \ "option, agree to xxx visit your camera", Preferredstyle:. Alert) Erroralert. Addaction(Uialertaction (title:"OK", Style:uialertactionstyle. Default, Handler:nil)) self. Presentviewcontroller(Erroralert, Animated:true, Completion:nil)} else {//input and output bridges, which coordinate the transfer of data from Intput to output. See word meaning, session-session) Capturesession = Avcapturesession () capturesession!. Addinput(captureinput)//output stream Let Capturemetadataoutput = Avcapturemetadataoutput ()//Limit scan area http ://blog. Csdn. NET/lc_obj/article/details/41549469Capturemetadataoutput. Rectofinterest= CGRectMake (128.0/screenwh. ScreenHeight, (SCREENWH. ScreenWidth-280.0)/SCREENWH. ScreenWidth*2.0,280.0/screenwh. ScreenHeight,280.0/screenwh. ScreenWidth) capturesession!. Addoutput(capturemetadataoutput)//join queue as specified must be serial capturemetadataoutput. Setmetadataobjectsdelegate(Self, Queue:dispatch_get_main_queue ())//Specify the type of information, QRCode, you know Capturemetadataoutput. Metadataobjecttypes= [Avmetadataobjecttypeqrcode]//Use this preview layer and image information capture session (session) to display the video Videopreviewlayer = Avcapturevideop Reviewlayer (session:capturesession!) videopreviewlayer!. Videogravity= Avlayervideogravityresizeaspectfill videopreviewlayer!. Frame= view. BoundsView. Layer. Addsublayer(videopreviewlayer!) } }

Ps:lz with the next and Sina Weibo sweep, found that the scan box is a bluff, that is, you did not take it to the two-dimensional code, only two-dimensional code into the mobile phone camera range, the line decoding success ....
So LZ in the code to do a scan area limit (feel pretty boring)

Implementing Agent Decoding
    // MARK:-Avcapturemetadataoutputobjectsdelegate func Captureoutput (Captureoutput: avcaptureoutput!, Didoutputmetadataobjectsmetadataobjects: [Anyobject]!, FromconnectionConnection: avcaptureconnection!) {ifMetadataobjects = = Nil | | Metadataobjects.count = =0{captureview!. frame = Cgrectzeroreturn}//Brushed out the data forMetadataObjectinchmetadataobjects {ifMetadataobject.type = = Avmetadataobjecttypeqrcode { Letmetadata = MetadataObject as! Avmetadatamachinereadablecodeobject//Metadata objects are converted to the coordinates of the layer LetCodecoord = videopreviewlayer!. Transformedmetadataobjectformetadataobject (metadata) as! Avmetadatamachinereadablecodeobject captureview!. frame = Codecoord.boundsifMetadata.stringvalue! = Nil {println ("\ (metadata.stringvalue)") self.capturesession!. Stoprunning () LetSuccessalert = Uialertcontroller (title:"Hint",message:"Open"+ Metadata.stringvalue,Preferredstyle: . Alert) successalert.addaction(uialertaction (title:"Cancel", Style:.) Default, Handler: {(_), Void  in Self.stopcapture ()}))                    Successalert.Addaction(uialertaction (title:"OK", style:.) Default, Handler: {(_), Void inif metadata.stringValue.lowercaseString.hasPrefix ("http"                            ) {uiapplication.sharedapplication (). OpenURL (Nsurl (string:metadata.stringValue)!) self.navigationcontroller!. Popviewcontrolleranimated (true)}))                                             Self.Presentviewcontroller(Successalert, animated: true, Completion:nil)}            }        }    }

Data to convert the AVMetadataMachineReadableCodeObject corresponding QR code.

Generate two-dimensional code
MARK:-Private Methods private func createqrforstring (qrstring:string, qrimagename:string?), UIImage? {if let sureqrstring = qrstring {Let StringData = sureqrstring. datausingencoding(nsutf8stringencoding, Allowlossyconversion:false)//Create a two-dimensional code filter Let Qrfilter = Cifilter (name:"Ciqrcodegenerator") Qrfilter. SetValue(StringData, Forkey:"InputMessage") Qrfilter. SetValue("H", Forkey:"Inputcorrectionlevel") Let Qrciimage = Qrfilter. OutputimageCreate a color filter, black and white let Colorfilter = Cifilter (name:"Cifalsecolor") Colorfilter. SetDefaults() Colorfilter. SetValue(Qrciimage, Forkey:"Inputimage") Colorfilter. SetValue(Cicolor (Red:0, Green:0, Blue:0), Forkey:"InputColor0") Colorfilter. SetValue(Cicolor (Red:1, Green:1, Blue:1), Forkey:"InputColor1")//Return two-dimensional code image let Codeimage = UIImage (ciimage:colorfilter. Outputimage. Imagebyapplyingtransform(Cgaffinetransformmakescale (5,5))//Usually, the QR code is customized, and the middle will put the image to express the meaning if let iconimage = UIImage (named:qrimagename!) {Let rect = CGRectMake (0,0, codeimage!. Size. Width, codeimage!. Size. Height) Uigraphicsbeginimagecontext (rect. Size) codeimage!. Drawinrect(rect) Let avatarsize = Cgsizemake (rect. Size. Width*0.25, rect. Size. Height*0.25) Letx= (rect. Width-Avatarsize. Width) *0.5Lety= (rect. Height-Avatarsize. Height) *0.5Iconimage. Drawinrect(CGRectMake (x,y, avatarsize. Width, avatarsize. Height)) Let Resultimage = Uigraphicsgetimagefromcurrentimagecontext () uigraphicsendimagecontext () Return resultimage} return codeimage} return nil}


The end: AVFoundation This frame is particularly powerful and can also be used to write your own definition camera, take photos and record videos, etc.

Swift avfoundation QR code scanning and generation

Related Article

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.