精华内容
下载资源
问答
  • 随处能看到二维码,比如商城里面,肯德基,餐厅等等,对于二维码扫描我们使用的是google的开源框架Zxing,我们可以去http://code.google.com/p/zxing/下载源码和Jar包,之前我项目中的二维码扫描功能只实现了扫描功能...
  • 了解二维码这个东西还是从微信中,当时微信推出二维码扫描功能,自己感觉挺新颖的,从一张图片中扫一下竟然能直接加好友,不可思议啊,那时候还不了解二维码,呵呵,然后做项目的时候,老板说要加上二维码扫描功能,...

    转载请注明出处:http://blog.csdn.net/xiaanming/article/details/10163203

    了解二维码这个东西还是从微信中,当时微信推出二维码扫描功能,自己感觉挺新颖的,从一张图片中扫一下竟然能直接加好友,不可思议啊,那时候还不了解二维码,呵呵,然后做项目的时候,老板说要加上二维码扫描功能,然后自己的屁颠屁颠的去百度,google啥的,发现很多朋友都有介绍二维码扫描的功能,然后我就跟着人家的介绍自己搞起了二维码扫描功能,跟着人家的帖子,很快我的项目就加入了扫描二维码的功能,然后自己还很开心。


    随着微信的到来,二维码越来越火爆,随处能看到二维码,比如商城里面,肯德基,餐厅等等,对于二维码扫描我们使用的是google的开源框架Zxing,我们可以去http://code.google.com/p/zxing/下载源码和Jar包,之前我项目中的二维码扫描功能只实现了扫描功能,其UI真的是其丑无比,一个好的应用软件,其UI界面也要被大众所接纳,不然人家就不会用你的软件啦,所以说应用软件功能和界面一样都很重要,例如微信,相信微信UI被很多应用软件所模仿,我也仿照微信扫描二维码效果进行模仿,虽然没有微信做的那么精致,但是效果还是可以的,所以将自己修改UI的代码和扫描二维码的代码分享给大家,一是自己以后项目遇到同样的功能直接拷贝来用,二是给还没有加入二维码功能的人一个参考,站在巨人的肩膀上,哈哈,我之前也是站在巨人的肩膀上加上此功能,接下来跟着我一步一步来实现此项功能,里面去除了很多不必要的文件


    我们先看下项目的结构


    • 如果你项目也想加入此功能,你直接将com.mining.app.zxing.camera,com.mining.app.zxing.decoding,com.mining.app.zxing.view这三个包拷贝到你的项目中,然后引入相对应的资源进去,我也是从我的项目中直接引用过来的,包名都没改呢,当然还需要引用Zxing.jar

    • com.example.qr_codescan包里面有一个MipcaActivityCapture,也是直接引入我之前项目的代码的,这个Activity主要处理扫描界面的类,比如,扫描成功有声音和振动等等,主要关注里面的handleDecode(Result result, Bitmap barcode)方法,扫描完成之后将扫描到的结果和二维码的bitmap当初参数传递到handleDecode(Result result, Bitmap barcode)里面,我们只需要在里面写出相对应的处理代码即可,其他的地方都不用改得,我这里处理扫描结果和扫描拍的照片

    	/**
    	 * 处理扫描结果
    	 * @param result
    	 * @param barcode
    	 */
    	public void handleDecode(Result result, Bitmap barcode) {
    		inactivityTimer.onActivity();
    		playBeepSoundAndVibrate();
    		String resultString = result.getText();
    		if (resultString.equals("")) {
    			Toast.makeText(MipcaActivityCapture.this, "Scan failed!", Toast.LENGTH_SHORT).show();
    		}else {
    			Intent resultIntent = new Intent();
    			Bundle bundle = new Bundle();
    			bundle.putString("result", resultString);
    			bundle.putParcelable("bitmap", barcode);
    			resultIntent.putExtras(bundle);
    			this.setResult(RESULT_OK, resultIntent);
    		}
    		MipcaActivityCapture.this.finish();
    	}

    • 我对MipcaActivityCapture界面的布局做了自己的改动,先看下效果图,主要是用到FrameLayout,里面嵌套RelativeLayout,里面的图片也是从微信里面拿出来的,平常我看到需要什么图片就去微信里面找,没有美工的公司的程序员就是苦逼


    布局代码如下

    <?xml version="1.0" encoding="utf-8"?>
    <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="fill_parent"
            android:layout_height="fill_parent" >
    
        <RelativeLayout
            android:layout_width="fill_parent"
            android:layout_height="fill_parent" >
    
            <SurfaceView
                android:id="@+id/preview_view"
                android:layout_width="fill_parent"
                android:layout_height="fill_parent"
                android:layout_gravity="center" />
    
            <com.mining.app.zxing.view.ViewfinderView
                android:id="@+id/viewfinder_view"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content" />
    
            <include
                android:id="@+id/include1"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:layout_alignParentTop="true"
                layout="@layout/activity_title" />
        </RelativeLayout>
    
    </FrameLayout>
    在里面我将界面上面部分写在另一个布局里面,然后include进来,因为这个activity_title在我项目里面还供其他的Activity使用,我也是直接拷贝出来的

    <?xml version="1.0" encoding="utf-8"?>
    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:background="@drawable/mmtitle_bg_alpha" >
    
        <Button
            android:id="@+id/button_back"
            android:layout_width="75.0dip"
            android:text="返回"
            android:background="@drawable/mm_title_back_btn"
            android:textColor="@android:color/white"
            android:layout_height="wrap_content"
            android:layout_centerVertical="true"
            android:layout_marginLeft="2dip" />
    
        <TextView
            android:id="@+id/textview_title"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignBaseline="@+id/button_back"
            android:layout_alignBottom="@+id/button_back"
            android:layout_centerHorizontal="true"
            android:gravity="center_vertical"
            android:text="二维码扫描"
            android:textColor="@android:color/white"
            android:textSize="18sp" />
    
    </RelativeLayout>
    • 在我这个demo里面,有一个主界面MainActivity,里面一个Button, 一个ImageView和一个TextView,点击Button进入到二维码扫描界面,当扫描OK的时候,回到主界面,将扫描的结果显示到TextView,将图片显示到ImageView里面,然后你可以不处理图片,我这里随带的加上图片,主界面的布局很简单如下

    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="#ffe1e0de" >
    
        <Button
            android:id="@+id/button1"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_alignParentTop="true"
            android:text="扫描二维码" />
    
        <TextView
            android:id="@+id/result"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_below="@+id/button1"
            android:lines="2"
            android:gravity="center_horizontal"
            android:textColor="@android:color/black"
            android:textSize="16sp" />
    
        <ImageView
            android:id="@+id/qrcode_bitmap"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:layout_alignParentLeft="true"
            android:layout_below="@+id/result"/>
    </RelativeLayout>
    • MainActivity里面的代码如下,里面的功能在上面已经说了

    package com.example.qr_codescan;
    
    
    import android.app.Activity;
    import android.content.Intent;
    import android.graphics.Bitmap;
    import android.os.Bundle;
    import android.view.View;
    import android.view.View.OnClickListener;
    import android.widget.Button;
    import android.widget.ImageView;
    import android.widget.TextView;
    
    public class MainActivity extends Activity {
    	private final static int SCANNIN_GREQUEST_CODE = 1;
    	/**
    	 * 显示扫描结果
    	 */
    	private TextView mTextView ;
    	/**
    	 * 显示扫描拍的图片
    	 */
    	private ImageView mImageView;
    	
    
    	@Override
    	protected void onCreate(Bundle savedInstanceState) {
    		super.onCreate(savedInstanceState);
    		setContentView(R.layout.activity_main);
    		
    		mTextView = (TextView) findViewById(R.id.result); 
    		mImageView = (ImageView) findViewById(R.id.qrcode_bitmap);
    		
    		//点击按钮跳转到二维码扫描界面,这里用的是startActivityForResult跳转
    		//扫描完了之后调到该界面
    		Button mButton = (Button) findViewById(R.id.button1);
    		mButton.setOnClickListener(new OnClickListener() {
    			
    			@Override
    			public void onClick(View v) {
    				Intent intent = new Intent();
    				intent.setClass(MainActivity.this, MipcaActivityCapture.class);
    				intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    				startActivityForResult(intent, SCANNIN_GREQUEST_CODE);
    			}
    		});
    	}
    	
    	
    	@Override
        protected void onActivityResult(int requestCode, int resultCode, Intent data) {
            super.onActivityResult(requestCode, resultCode, data);
            switch (requestCode) {
    		case SCANNIN_GREQUEST_CODE:
    			if(resultCode == RESULT_OK){
    				Bundle bundle = data.getExtras();
    				//显示扫描到的内容
    				mTextView.setText(bundle.getString("result"));
    				//显示
    				mImageView.setImageBitmap((Bitmap) data.getParcelableExtra("bitmap"));
    			}
    			break;
    		}
        }	
    
    }
    


    • 上面的代码还是比较简单,但是要想做出像微信那样只的扫描框,紧紧上面的代码是没有那种效果的,我们必须重写com.mining.app.zxing.view包下面的ViewfinderView类,微信里面的都是用的图片,我是自己画出来的,代码注释的比较清楚,大家直接看代码吧,相信你能理解的,如果你要修改扫描框的大小,去CameraManager类里面修改

    /*
     * Copyright (C) 2008 ZXing authors
     *
     * Licensed under the Apache License, Version 2.0 (the "License");
     * you may not use this file except in compliance with the License.
     * You may obtain a copy of the License at
     *
     *      http://www.apache.org/licenses/LICENSE-2.0
     *
     * Unless required by applicable law or agreed to in writing, software
     * distributed under the License is distributed on an "AS IS" BASIS,
     * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     * See the License for the specific language governing permissions and
     * limitations under the License.
     */
    
    package com.mining.app.zxing.view;
    
    import java.util.Collection;
    import java.util.HashSet;
    
    import android.content.Context;
    import android.content.res.Resources;
    import android.graphics.Bitmap;
    import android.graphics.Canvas;
    import android.graphics.Color;
    import android.graphics.Paint;
    import android.graphics.Rect;
    import android.graphics.Typeface;
    import android.util.AttributeSet;
    import android.view.View;
    
    import com.example.qr_codescan.R;
    import com.google.zxing.ResultPoint;
    import com.mining.app.zxing.camera.CameraManager;
    
    /**
     * This view is overlaid on top of the camera preview. It adds the viewfinder
     * rectangle and partial transparency outside it, as well as the laser scanner
     * animation and result points.
     * 
     */
    public final class ViewfinderView extends View {
    	private static final String TAG = "log";
    	/**
    	 * 刷新界面的时间
    	 */
    	private static final long ANIMATION_DELAY = 10L;
    	private static final int OPAQUE = 0xFF;
    
    	/**
    	 * 四个绿色边角对应的长度
    	 */
    	private int ScreenRate;
    	
    	/**
    	 * 四个绿色边角对应的宽度
    	 */
    	private static final int CORNER_WIDTH = 10;
    	/**
    	 * 扫描框中的中间线的宽度
    	 */
    	private static final int MIDDLE_LINE_WIDTH = 6;
    	
    	/**
    	 * 扫描框中的中间线的与扫描框左右的间隙
    	 */
    	private static final int MIDDLE_LINE_PADDING = 5;
    	
    	/**
    	 * 中间那条线每次刷新移动的距离
    	 */
    	private static final int SPEEN_DISTANCE = 5;
    	
    	/**
    	 * 手机的屏幕密度
    	 */
    	private static float density;
    	/**
    	 * 字体大小
    	 */
    	private static final int TEXT_SIZE = 16;
    	/**
    	 * 字体距离扫描框下面的距离
    	 */
    	private static final int TEXT_PADDING_TOP = 30;
    	
    	/**
    	 * 画笔对象的引用
    	 */
    	private Paint paint;
    	
    	/**
    	 * 中间滑动线的最顶端位置
    	 */
    	private int slideTop;
    	
    	/**
    	 * 中间滑动线的最底端位置
    	 */
    	private int slideBottom;
    	
    	private Bitmap resultBitmap;
    	private final int maskColor;
    	private final int resultColor;
    	
    	private final int resultPointColor;
    	private Collection<ResultPoint> possibleResultPoints;
    	private Collection<ResultPoint> lastPossibleResultPoints;
    
    	boolean isFirst;
    	
    	public ViewfinderView(Context context, AttributeSet attrs) {
    		super(context, attrs);
    		
    		density = context.getResources().getDisplayMetrics().density;
    		//将像素转换成dp
    		ScreenRate = (int)(20 * density);
    
    		paint = new Paint();
    		Resources resources = getResources();
    		maskColor = resources.getColor(R.color.viewfinder_mask);
    		resultColor = resources.getColor(R.color.result_view);
    
    		resultPointColor = resources.getColor(R.color.possible_result_points);
    		possibleResultPoints = new HashSet<ResultPoint>(5);
    	}
    
    	@Override
    	public void onDraw(Canvas canvas) {
    		//中间的扫描框,你要修改扫描框的大小,去CameraManager里面修改
    		Rect frame = CameraManager.get().getFramingRect();
    		if (frame == null) {
    			return;
    		}
    		
    		//初始化中间线滑动的最上边和最下边
    		if(!isFirst){
    			isFirst = true;
    			slideTop = frame.top;
    			slideBottom = frame.bottom;
    		}
    		
    		//获取屏幕的宽和高
    		int width = canvas.getWidth();
    		int height = canvas.getHeight();
    
    		paint.setColor(resultBitmap != null ? resultColor : maskColor);
    		
    		//画出扫描框外面的阴影部分,共四个部分,扫描框的上面到屏幕上面,扫描框的下面到屏幕下面
    		//扫描框的左边面到屏幕左边,扫描框的右边到屏幕右边
    		canvas.drawRect(0, 0, width, frame.top, paint);
    		canvas.drawRect(0, frame.top, frame.left, frame.bottom + 1, paint);
    		canvas.drawRect(frame.right + 1, frame.top, width, frame.bottom + 1,
    				paint);
    		canvas.drawRect(0, frame.bottom + 1, width, height, paint);
    		
    		
    
    		if (resultBitmap != null) {
    			// Draw the opaque result bitmap over the scanning rectangle
    			paint.setAlpha(OPAQUE);
    			canvas.drawBitmap(resultBitmap, frame.left, frame.top, paint);
    		} else {
    
    			//画扫描框边上的角,总共8个部分
    			paint.setColor(Color.GREEN);
    			canvas.drawRect(frame.left, frame.top, frame.left + ScreenRate,
    					frame.top + CORNER_WIDTH, paint);
    			canvas.drawRect(frame.left, frame.top, frame.left + CORNER_WIDTH, frame.top
    					+ ScreenRate, paint);
    			canvas.drawRect(frame.right - ScreenRate, frame.top, frame.right,
    					frame.top + CORNER_WIDTH, paint);
    			canvas.drawRect(frame.right - CORNER_WIDTH, frame.top, frame.right, frame.top
    					+ ScreenRate, paint);
    			canvas.drawRect(frame.left, frame.bottom - CORNER_WIDTH, frame.left
    					+ ScreenRate, frame.bottom, paint);
    			canvas.drawRect(frame.left, frame.bottom - ScreenRate,
    					frame.left + CORNER_WIDTH, frame.bottom, paint);
    			canvas.drawRect(frame.right - ScreenRate, frame.bottom - CORNER_WIDTH,
    					frame.right, frame.bottom, paint);
    			canvas.drawRect(frame.right - CORNER_WIDTH, frame.bottom - ScreenRate,
    					frame.right, frame.bottom, paint);
    
    			
    			//绘制中间的线,每次刷新界面,中间的线往下移动SPEEN_DISTANCE
    			slideTop += SPEEN_DISTANCE;
    			if(slideTop >= frame.bottom){
    				slideTop = frame.top;
    			}
    			canvas.drawRect(frame.left + MIDDLE_LINE_PADDING, slideTop - MIDDLE_LINE_WIDTH/2, frame.right - MIDDLE_LINE_PADDING,slideTop + MIDDLE_LINE_WIDTH/2, paint);
    			
    			
    			//画扫描框下面的字
    			paint.setColor(Color.WHITE);
    			paint.setTextSize(TEXT_SIZE * density);
    			paint.setAlpha(0x40);
    			paint.setTypeface(Typeface.create("System", Typeface.BOLD));
    			canvas.drawText(getResources().getString(R.string.scan_text), frame.left, (float) (frame.bottom + (float)TEXT_PADDING_TOP *density), paint);
    			
    			
    
    			Collection<ResultPoint> currentPossible = possibleResultPoints;
    			Collection<ResultPoint> currentLast = lastPossibleResultPoints;
    			if (currentPossible.isEmpty()) {
    				lastPossibleResultPoints = null;
    			} else {
    				possibleResultPoints = new HashSet<ResultPoint>(5);
    				lastPossibleResultPoints = currentPossible;
    				paint.setAlpha(OPAQUE);
    				paint.setColor(resultPointColor);
    				for (ResultPoint point : currentPossible) {
    					canvas.drawCircle(frame.left + point.getX(), frame.top
    							+ point.getY(), 6.0f, paint);
    				}
    			}
    			if (currentLast != null) {
    				paint.setAlpha(OPAQUE / 2);
    				paint.setColor(resultPointColor);
    				for (ResultPoint point : currentLast) {
    					canvas.drawCircle(frame.left + point.getX(), frame.top
    							+ point.getY(), 3.0f, paint);
    				}
    			}
    
    			
    			//只刷新扫描框的内容,其他地方不刷新
    			postInvalidateDelayed(ANIMATION_DELAY, frame.left, frame.top,
    					frame.right, frame.bottom);
    			
    		}
    	}
    
    	public void drawViewfinder() {
    		resultBitmap = null;
    		invalidate();
    	}
    
    	/**
    	 * Draw a bitmap with the result points highlighted instead of the live
    	 * scanning display.
    	 * 
    	 * @param barcode
    	 *            An image of the decoded barcode.
    	 */
    	public void drawResultBitmap(Bitmap barcode) {
    		resultBitmap = barcode;
    		invalidate();
    	}
    
    	public void addPossibleResultPoint(ResultPoint point) {
    		possibleResultPoints.add(point);
    	}
    
    }
    

    上面的代码中,中间那根线微信是用的图片,我这里是画的,如果你想更加仿真点就将下面的代码

    canvas.drawRect(frame.left + MIDDLE_LINE_PADDING, slideTop - MIDDLE_LINE_WIDTH/2, frame.right - MIDDLE_LINE_PADDING,slideTop + MIDDLE_LINE_WIDTH/2, paint);

    改成

    Rect lineRect = new Rect();
    			lineRect.left = frame.left;
    			lineRect.right = frame.right;
    			lineRect.top = slideTop;
    			lineRect.bottom = slideTop + 18;
    			canvas.drawBitmap(((BitmapDrawable)(getResources().getDrawable(R.drawable.qrcode_scan_line))).getBitmap(), null, lineRect, paint);

    那条扫描线自己去微信里面找一下,我贴出来的失真了,下载微信apk,将后缀名改成zip,然后解压就行了

    画扫描框下面字体的代码需要修改下,这样子能根据字体自动排列在中间,如果字太长我没有处理,那个要自动换行,你可以自行处理

    paint.setColor(Color.WHITE);  
    paint.setTextSize(TEXT_SIZE * density);  
    paint.setAlpha(0x40);  
    paint.setTypeface(Typeface.DEFAULT_BOLD); 
    String text = getResources().getString(R.string.R.string.scan_text);
    float textWidth = paint.measureText(text);
    
    canvas.drawText(text, (width - textWidth)/2, (float) (frame.bottom + (float)TEXT_PADDING_TOP *density), paint)

    运行界面截图,其中中间的那根绿色的线会上下移动,跟微信的效果差不多,当然运行你还需要相对应的权限问题,有兴趣的朋友可以去下载demo



    从8点多写这篇博客写到现在,看起来这么点字,但实际上还是比较耗时间的,如果你觉得这篇文章对你有帮助,你就顶一下,哈哈,洗澡睡觉去了,上面的项目中还有一些资源文件我没有贴出来,想要看效果可以下载源码


    我在Android 基于google Zxing实现对手机中的二维码进行扫描这篇文章中实现了对手机中二维码照片的扫描,并且替换了中间的扫描线,和微信效果更加相似,建议大家去下那文章的项目源码


    项目源码,点击下载




    展开全文
  • 条形码、二维码扫描、生成Demo 完整源码

    万次下载 热门讨论 2012-08-05 12:58:49
    使用Google ZXing开源项目制作的条形码、二维码的生成、扫描Demo
  • AVFoundation二维码扫描,二维码扫描,图片的无损放大

    二维码扫描

    扫描实现思路

    • 二维码实现思路

      1. 输入设备(用来获取外界信息) 摄像头, 麦克风, 键盘
      2. 输出设备 (将收集到的信息, 做解析, 来获取收到的内容)
      3. 会话session (用来连接输入和输出设备)
      4. 特殊的layer (展示输入设备所采集的信息)

      下面上代码:

      //
      // ViewController.m
      // 二维码
      //
      // Created by VolitationXiaoXing on 15/12/17.
      // Copyright © 2016年 dream. All rights reserved.
      //

     #import "ViewController.h"
     #import <AVFoundation/AVFoundation.h>
     #import "HMPreView.h"
    
     @interface ViewController ()<AVCaptureMetadataOutputObjectsDelegate>
     //1. 输入设备(用来获取外界信息)  摄像头, 麦克风, 键盘
     @property (nonatomic, strong) AVCaptureDeviceInput *input;
    
     //2. 输出设备 (将收集到的信息, 做解析, 来获取收到的内容)
    @property (nonatomic, strong) AVCaptureMetadataOutput *output;
    
     //3. 会话session (用来连接输入和输出设备)
    @property (nonatomic, strong) AVCaptureSession *session;
    
     //4. 特殊的layer (展示输入设备所采集的信息)
      //@property (nonatomic, strong) AVCaptureVideoPreviewLayer *previewLayer;
     @property (nonatomic, strong) HMPreView *preview;
    
     @property (weak, nonatomic) IBOutlet UILabel *label;
    
    
     @end
    
     @implementation ViewController
    
     - (void)viewDidLoad {
        [super viewDidLoad];
        // Do any additional setup after loading the view, typically from a nib.
    
    
     }
    
     #pragma mark 点击屏幕开始扫描
    - (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
    {
        //1.输入设备(用来获取外界信息)  摄像头, 麦克风, 键盘
        AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
        self.input = [AVCaptureDeviceInput deviceInputWithDevice:device error:nil];
    
      //2.输出设备 (将收集到的信息, 做解析, 来获取收到的内容)
      self.output = [AVCaptureMetadataOutput new];
    
      //3.会话session (用来连接输入和输出设备)
        self.session = [AVCaptureSession new];
    
     // 会话扫描展示的大小
    [self.session setSessionPreset:AVCaptureSessionPresetHigh];
    
     // 会话跟输入和输出设备关联
    if ([self.session canAddInput:self.input]) {
        [self.session addInput:self.input];
    }
    if ([self.session canAddOutput:self.output]) {
         [self.session addOutput:self.output]; 
    }
    
        //下面两句代码应该写在此处
        //制定输出设备的代理, 用来接受返回的数据
        [self.output setMetadataObjectsDelegate:self queue:dispatch_get_main_queue()];
    
        //设置元数据类型 二维码QRCode
        [self.output setMetadataObjectTypes:@[AVMetadataObjectTypeQRCode]];
    
        //4.特殊的layer (展示输入设备所采集的信息)
        //self.previewLayer = [[AVCaptureVideoPreviewLayer alloc] initWithSession:self.session];
        // 大小layer的大小
        //self.previewLayer.frame = self.view.bounds;
        //[self.view.layer addSublayer:self.previewLayer];
    
        //这个View是一个自定义的View,就是中间一个正方形,中间有一个线上下扫动
        self.preview = [[HMPreView alloc] initWithFrame:self.view.bounds];
    
        self.preview.session = self.session;
    
        [self.view addSubview:self.preview];
    
        //5. 启动会话
        [self.session startRunning];
    }
    
     /**
     captureOutput : 输出设备
     metadataObjects : 元数据对象的数组
     connection : 连接
      */
     - (void)captureOutput:(AVCaptureOutput *)captureOutput didOutputMetadataObjects:(NSArray *)metadataObjects fromConnection:(AVCaptureConnection *)connection
    {
        //1. 停止会话
        [self.session stopRunning];
    
        //2. 删除layer
        //[self.previewLayer removeFromSuperlayer];
        [self.preview removeFromSuperview];
    
        //3. 遍历数据获取内容
        for (AVMetadataMachineReadableCodeObject *obj in metadataObjects) {
            //NSLog(@"obj: %@",obj.stringValue);
            self.label.text = obj.stringValue;
        }
    }
    
     @end
    
    
    

    生成二维码

    下面是生成二维码的代码,包括了无损放大图片

       //
    //  ViewController.m
    //  QRCodeCreat
    //
    //  Created by VolitationXiaoXing on 16/7/14.
    //  Copyright © 2016年 itcast. All rights reserved.
    //
    
     #import "ViewController.h"
    
     @interface ViewController ()
    
     @property (weak, nonatomic) IBOutlet UIImageView *imgView;
    
     @end
    
     @implementation ViewController
    
     - (void)viewDidLoad {
        [super viewDidLoad];
    
        CIFilter *filter = [CIFilter filterWithName:@"CIQRCodeGenerator"];
    
        [filter setDefaults];
    
        NSData *data = [@"这个是二维码中的数据" dataUsingEncoding:NSUTF8StringEncoding];
    
        [filter setValue:data forKey:@"inputMessage"];
        //设置容错率
        [filter setValue:@"H" forKey:@"inputCorrectionLevel"];
    
        CIImage *coreImage = [filter outputImage];
    
        //  1.无损放大图片
        UIImage *QRImage = [self imageWithCIImage:coreImage andSize:self.imgView.bounds.size];
    
    
    
        //  2.合并头像
        CGSize headSize = CGSizeMake(self.imgView.bounds.size.width * 0.3, self.imgView.bounds.size.height * 0.3);
    
        UIImage *overImage = [self imageWithBackgroundImage:QRImage centerImage:[UIImage imageNamed:@"head"] centerImageSize:headSize];
    
        self.imgView.image = overImage;
    
     }
    
     //  1.无损放大图片这里用到了CIImage与CGImage与UIImage转换
    
     - (UIImage *)imageWithCIImage:(CIImage *)coreImage andSize:(CGSize)size{
    
        // 1.CIImage --> CGImage
        CIContext *tempContext = [CIContext contextWithOptions:nil];
    
        CGImageRef originCGImage = [tempContext createCGImage:coreImage fromRect:coreImage.extent];
    
        // 2.创建和size一样大的图形上下文(Bitmap)
        CGColorSpaceRef cs = CGColorSpaceCreateDeviceGray();
    
        CGContextRef bitmapCtx = CGBitmapContextCreate(NULL, size.width, size.height, 8, 0, cs, kCGImageAlphaNone);
    
        // 3.CGImage 渲染到上下文中
        CGContextSetInterpolationQuality(bitmapCtx, kCGInterpolationNone);
    
        CGContextDrawImage(bitmapCtx, CGRectMake(0, 0, size.width, size.height), originCGImage);
    
        // 4.将图形上下文中的图像取出来
        CGImageRef QRImage = CGBitmapContextCreateImage(bitmapCtx);
    
        //  释放
    
        // return
        return [UIImage imageWithCGImage:QRImage];
    
     }
    
    
     //  2.合并头像
    
     - (UIImage *)imageWithBackgroundImage:(UIImage *)backgroundImage centerImage:(UIImage *)centerImage centerImageSize:(CGSize)centerSize{
    
        // 1.开启图形上下文
        UIGraphicsBeginImageContext(backgroundImage.size);
    
        // 2.先画背景
        [backgroundImage drawAtPoint:CGPointZero];
    
        // 3.画头像
        CGFloat headW = centerSize.width;
        CGFloat headH = centerSize.height;
        CGFloat headX = (backgroundImage.size.width - headW) * 0.5;
        CGFloat headY = (backgroundImage.size.width - headH) * 0.5;
    
        [centerImage drawInRect:CGRectMake(headX, headY, headW, headH)];
    
        // 4.取图像
        UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
    
        UIGraphicsEndImageContext();
    
        return newImage;
    
     }
    
    
    
     @end
    
    
    
    
    展开全文
  • 非常感谢大家利用自己宝贵的时间来阅读我的文章 , 今天给大家带来的是一个原生二维码扫描的demo,很久之前写的代码,最近项目要用,想着以后用到的可能性也挺大的,就翻出来整理了个demo出来,如果需要的可以做个...

    非常感谢大家利用自己宝贵的时间来阅读我的文章 ,  今天给大家带来的是一个原生二维码扫描的demo,很久之前写的代码,最近项目要用,想着以后用到的可能性也挺大的,就翻出来整理了个demo出来,如果需要的可以做个参考。如果需要的话希望能帮到你 , 当然, 有任何不妥的地方 欢迎指正。喜欢的可以关注一下我的博客我的简书

    老规矩,先上效果展示



    卧槽,这个gif为何如此之大。。。不管了,上demo地址ZQScanTool


    用法很简单,把ZQScanTool文件夹拖入到项目中,在需要跳转扫描的时候把ScanViewController给Push出来

    ScanViewController *vc = [[ScanViewController alloc] init];
    
        [self.navigationController pushViewController:vc animated:YES];


    把扫描结果展示控制器ScanResultViewController换成你的调转页

    到这里就不用看了,下demo去吧。。。

    主要代码:

    1、相机设置

    - (void)instanceDevice{
    
    
    
        line_tag = 1872637;
    
        //获取摄像设备
    
        AVCaptureDevice * device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    
        //创建输入流
    
        AVCaptureDeviceInput * input = [AVCaptureDeviceInput deviceInputWithDevice:device error:nil];
    
        //创建输出流
    
        AVCaptureMetadataOutput * output = [[AVCaptureMetadataOutput alloc]init];
    
        //设置代理 在主线程里刷新
    
        [output setMetadataObjectsDelegate:self queue:dispatch_get_main_queue()];
    
    
    
        //初始化链接对象
    
        session = [[AVCaptureSession alloc]init];
    
        //高质量采集率
    
        [session setSessionPreset:AVCaptureSessionPresetHigh];
    
        if (input) {
    
            [session addInput:input];
    
        }
    
        if (output) {
    
            [session addOutput:output];
    
            //设置扫码支持的编码格式(如下设置条形码和二维码兼容)
    
            NSMutableArray *a = [[NSMutableArray alloc] init];
    
            if ([output.availableMetadataObjectTypes containsObject:AVMetadataObjectTypeQRCode]) {
    
                [a addObject:AVMetadataObjectTypeQRCode];
    
            }
    
            if ([output.availableMetadataObjectTypes containsObject:AVMetadataObjectTypeEAN13Code]) {
    
                [a addObject:AVMetadataObjectTypeEAN13Code];
    
            }
    
            if ([output.availableMetadataObjectTypes containsObject:AVMetadataObjectTypeEAN8Code]) {
    
                [a addObject:AVMetadataObjectTypeEAN8Code];
    
            }
    
            if ([output.availableMetadataObjectTypes containsObject:AVMetadataObjectTypeCode128Code]) {
    
                [a addObject:AVMetadataObjectTypeCode128Code];
    
            }
    
            output.metadataObjectTypes=a;
    
        }
    
        AVCaptureVideoPreviewLayer * layer = [AVCaptureVideoPreviewLayer layerWithSession:session];
    
        layer.videoGravity=AVLayerVideoGravityResizeAspectFill;
    
        layer.frame=self.view.layer.bounds;
    
        [self.view.layer insertSublayer:layer atIndex:0];
    
    
    
        [self setOverlayPickerView];
    
    
    
        [session addObserver:self forKeyPath:@"running" options:NSKeyValueObservingOptionNew context:nil];
    
    
    
        //开始捕获
    
        [session startRunning];
    
    }
    

    2、扫描UI

    - (void)setOverlayPickerView
    
    {
    
        //左侧的view
    
        UIImageView *leftView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 30, ScreenHeight)];
    
        leftView.alpha = 0.5;
    
        leftView.backgroundColor = [UIColor blackColor];
    
        [self.view addSubview:leftView];
    
        //右侧的view
    
        UIImageView *rightView = [[UIImageView alloc] initWithFrame:CGRectMake(ScreenWidth-30, 0, 30, ScreenHeight)];
    
        rightView.alpha = 0.5;
    
        rightView.backgroundColor = [UIColor blackColor];
    
        [self.view addSubview:rightView];
    
        //最上部view
    
        UIImageView* upView = [[UIImageView alloc] initWithFrame:CGRectMake(30, 0, ScreenWidth - 60, (self.view.center.y-(ScreenWidth-60)/2))];
    
        upView.alpha = 0.5;
    
        upView.backgroundColor = [UIColor blackColor];
    
        [self.view addSubview:upView];
    
        UIButton *cancleBtn = [[UIButton alloc] initWithFrame:CGRectMake(5, 20, 44, 44)];
    
        [cancleBtn setImage:[UIImage imageNamed:@"nav_backButton_image"] forState:UIControlStateNormal];
    
        [cancleBtn addTarget:self action:@selector(cancleBtnClick) forControlEvents:UIControlEventTouchUpInside];
    
        [self.view addSubview:cancleBtn];
    
        //底部view
    
        UIImageView * downView = [[UIImageView alloc] initWithFrame:CGRectMake(30, (self.view.center.y+(ScreenWidth-60)/2), (ScreenWidth-60), (ScreenHeight-(self.view.center.y-(ScreenWidth-60)/2)))];
    
        downView.alpha = 0.5;
    
        downView.backgroundColor = [UIColor blackColor];
    
        [self.view addSubview:downView];
    
        UIImageView *centerView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth-60, ScreenHeight-60)];
    
        centerView.center = self.view.center;
    
        centerView.image = [UIImage imageNamed:@"scan_circle"];
    
        centerView.contentMode = UIViewContentModeScaleAspectFit;
    
        centerView.backgroundColor = [UIColor clearColor];
    
        [self.view addSubview:centerView];
    
        UIImageView *line = [[UIImageView alloc] initWithFrame:CGRectMake(30, CGRectGetMaxY(upView.frame), ScreenWidth-60, 2)];
    
        line.tag = line_tag;
    
        line.image = [UIImage imageNamed:@"scan_line"];
    
        line.contentMode = UIViewContentModeScaleAspectFill;
    
        line.backgroundColor = [UIColor clearColor];
    
        [self.view addSubview:line];
    
        UILabel *msg = [[UILabel alloc] initWithFrame:CGRectMake(30, CGRectGetMinY(downView.frame), ScreenWidth-60, 60)];
    
        msg.backgroundColor = [UIColor clearColor];
    
        msg.textColor = [UIColor whiteColor];
    
        msg.textAlignment = NSTextAlignmentCenter;
    
        msg.font = [UIFont systemFontOfSize:16];
    
        msg.text = @"将二维码放入框内,即可自动扫描";
    
        [self.view addSubview:msg];
    
    }
    

    3、扫描动画


    /**
    
    *
    
    *  监听扫码状态-修改扫描动画
    
    *
    
    */
    
    - (void)observeValueForKeyPath:(NSString *)keyPath
    
                          ofObject:(id)object
    
                            change:(NSDictionary *)change
    
                          context:(void *)context{
    
        if ([object isKindOfClass:[AVCaptureSession class]]) {
    
            BOOL isRunning = ((AVCaptureSession *)object).isRunning;
    
            if (isRunning) {
    
                [self addAnimation];
    
            }else{
    
                [self removeAnimation];
    
            }
    
        }
    
    }

    *  添加扫码动画

    - (void)addAnimation{
    
        UIView *line = [self.view viewWithTag:line_tag];
    
        line.hidden = NO;
    
        CABasicAnimation *animation = [ScanViewController moveYTime:2 fromY:[NSNumber numberWithFloat:0] toY:[NSNumber numberWithFloat:ScreenWidth-60-2] rep:OPEN_MAX];
    
        [line.layer addAnimation:animation forKey:@"LineAnimation"];
    
    }

     *去除扫码动画

    - (void)removeAnimation{
    
        UIView *line = [self.view viewWithTag:line_tag];
    
        [line.layer removeAnimationForKey:@"LineAnimation"];
    
        line.hidden = YES;
    
    }
    + (CABasicAnimation *)moveYTime:(float)time fromY:(NSNumber *)fromY toY:(NSNumber *)toY rep:(int)rep
    
    {
    
        CABasicAnimation *animationMove = [CABasicAnimation animationWithKeyPath:@"transform.translation.y"];
    
        [animationMove setFromValue:fromY];
    
        [animationMove setToValue:toY];
    
        animationMove.duration = time;
    
        animationMove.delegate = self;
    
        animationMove.repeatCount  = rep;
    
        animationMove.fillMode = kCAFillModeForwards;
    
        animationMove.removedOnCompletion = NO;
    
        animationMove.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
    
        return animationMove;
    
    }
    

    3、扫描结果

    -(void)captureOutput:(AVCaptureOutput *)captureOutput didOutputMetadataObjects:(NSArray *)metadataObjects fromConnection:(AVCaptureConnection *)connection{
    
        if (metadataObjects.count>0) {
    
            [session stopRunning];
    
            NSURL *url=[[NSBundle mainBundle]URLForResource:@"scanSuccess.wav" withExtension:nil];
    
                //2.加载音效文件,创建音效ID(SoundID,一个ID对应一个音效文件)
    
                SystemSoundID soundID=8787;
    
                AudioServicesCreateSystemSoundID((__bridge CFURLRef)url, &soundID);
    
                //3.播放音效文件
    
                //下面的两个函数都可以用来播放音效文件,第一个函数伴随有震动效果
    
                AudioServicesPlayAlertSound(soundID);
    
            AudioServicesPlaySystemSound(8787);
    
            AVMetadataMachineReadableCodeObject * metadataObject = [metadataObjects objectAtIndex :0];
    
            //输出扫描字符串
    
            NSString *data = metadataObject.stringValue;
    
            ScanResultViewController *resultVC = [[ScanResultViewController alloc] init];
    
            resultVC.title = @"扫描结果";
    
            resultVC.result = data;
    
            [self.navigationController pushViewController:resultVC animated:YES];
    
        }
    
    }

    @#%¥¥#&……¥#@!#!@¥@#%¥¥!@#!@#!说了不用看了,恩,就这么多了。好用别忘了点赞!



    展开全文
  • 二维码扫描

    千次阅读 2016-06-20 15:21:45
    二维码扫描,AVFoundation,ZBar,
       本文中我们介绍一下如何在iOS平台实现二维码扫描,我们可以借助一些优秀的第三方库,比如ZBar SDK和ZXing。在iOS7.0之后,我们也可以使用iOS系统原生扫描,通过AVFoundation框架来实现二维码扫描,不过AVFoundation框架不能识别相册中的二维码图片。
    

    1. 通过AVFoundation框架识别二维码

    1.1 AVFoundation框架扫描二维码的基本方法

    我们先来介绍一下如何使用AVFoundation框架实现二维码扫描。在iOS7之后,苹果自身提供了二维码的扫描功能,从效率上来说,原生的二维码远高于这些第三方框架。之前我们使用AVFoundation框架实现过拍照功能,基本的原理差不多类似;需要AVCaptureSession对象管理输入流和输出流;需要一个AVCaptureVideoPreviewLayer对象来显示信息。基本流程如下:
    这里写图片描述

    图中涉及到的几个相关类的说明如下:

    • AVCaptureSession 管理输入(AVCaptureInput)和输出(AVCaptureOutput)流,包含开启和停止会话方法。
    • AVCaptureDeviceInput 是AVCaptureInput的子类,可以作为输入捕获会话,用AVCaptureDevice实例初始化。
    • AVCaptureDevice 代表了物理捕获设备如:摄像机。用于配置等底层硬件设置相机的自动对焦模式。
    • AVCaptureMetadataOutput 是AVCaptureOutput的子类,处理输出捕获会话。捕获的对象传递给一个委托实现AVCaptureMetadataOutputObjectsDelegate协议。协议方法在指定的派发队列(dispatch queue)上执行。
    • AVCaptureVideoPreviewLayerCALayer的一个子类,显示捕获到的相机输出流。

    下面我们看一下具体的实现步骤:
    示例代码:

    #import "ViewController.h"
    #import <AVFoundation/AVFoundation.h>
    
    @interface ViewController ()<AVCaptureMetadataOutputObjectsDelegate>
    
    @property (weak, nonatomic) IBOutlet UISwitch *lightSwitch;// 闪光开关
    @property (nonatomic) AVCaptureSession *captureSession;//捕获的管理会话
    @property (nonatomic) AVCaptureVideoPreviewLayer *previewLayer;// 预览图层
    
    @end
    
    @implementation ViewController
    
    - (void)viewDidLoad {
        [super viewDidLoad];
    }
    
    // 开始二维码扫描
    - (IBAction)startScan:(UIButton *)sender {
    
        // 1. 初始化捕获会话,并添加输入对象
        self.captureSession = [[AVCaptureSession alloc] init];
    
        // 2. 初始化捕获设备对象AVCaptureDevice
        AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    
        // 3. 初始化捕获设备的输入对象AVCaptureDeviceInput
        AVCaptureDeviceInput *input = [AVCaptureDeviceInput deviceInputWithDevice:device error:nil];
        if (input == nil) {
            NSLog(@"输入对象初始化失败");
            return;
        }
    
        // 将输入对象添加到会话
        [self.captureSession addInput:input];
    
        // 4. 初始化输出对象AVCaptureMetadataOutput
        AVCaptureMetadataOutput *output = [[AVCaptureMetadataOutput alloc] init];
    
        // 将输出对象添加到会话
        [self.captureSession addOutput:output];
        // 设置输出对象源数据类型:AVMetadataObjectTypeQRCode条码类型
        [output setMetadataObjectTypes:@[AVMetadataObjectTypeQRCode]];
        // 设置输出对象代理,并实现代理方法
        [output setMetadataObjectsDelegate:self queue:dispatch_get_main_queue()];
    
        // 设置扫码区域为预览区域 默认全屏扫描
        CGFloat w = self.view.frame.size.width;
        CGFloat h = self.view.frame.size.height;
        // rectOfInterest属性:区域大小是相对于设备的大小的,默认值是(0, 0, 1, 1)。但是区域的坐标系统X和Y是互换的,同时,宽高的比例也互换了。
        [output setRectOfInterest:CGRectMake((h/2 -100)/h, (w/2 -100)/w, 200/h, 200/w)];
        NSLog(@"%@",NSStringFromCGRect(output.rectOfInterest));
    
        // 5. 初始化预览图层
        self.previewLayer = [[AVCaptureVideoPreviewLayer alloc] initWithSession:self.captureSession];
        self.previewLayer.videoGravity = AVLayerVideoGravityResizeAspectFill;// 拉伸属性
        self.previewLayer.frame = self.view.bounds;
        [self.view.layer addSublayer:self.previewLayer];
    
        // 6.开始会话
        [self.captureSession startRunning];
    
        // 关闭闪光灯
        self.lightSwitch.on = NO;
        [self.view bringSubviewToFront:self.lightSwitch];
    }
    
    #pragma mark -
    #pragma mark - AVCaptureMetadataOutputObjectsDelegate
    // 此方法是在识别到QRCode,并且完成转换。如果QRCode的内容越大,转换需要的时间就越长
    - (void)captureOutput:(AVCaptureOutput *)captureOutput didOutputMetadataObjects:(NSArray *)metadataObjects fromConnection:(AVCaptureConnection *)connection {
    
        if (metadataObjects != nil && [metadataObjects count] > 0) {
    
            // 扫码成功 停止扫描,
            [self.captureSession stopRunning];
    
            // 获取扫码结果:
            AVMetadataMachineReadableCodeObject *metadataObj = [metadataObjects objectAtIndex:0];
            NSString *result;
            if ([[metadataObj type] isEqualToString:AVMetadataObjectTypeQRCode]) {
                result = metadataObj.stringValue;
                NSLog(@"%@",result);
            } else {
                NSLog(@"不是二维码");
            }
        }
    }
    
    #pragma mark -
    #pragma mark - 开启闪光灯
    - (IBAction)lightOpenOrClose:(UISwitch *)sender {
    
        BOOL isOpen = sender.on;
        // 获取设备
        AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
        if ([device hasTorch]) {
            [device lockForConfiguration:nil];
            if (isOpen) {
                [device setTorchMode:AVCaptureTorchModeOn];
            } else {
                [device setTorchMode:AVCaptureTorchModeOff];
            }
            [device unlockForConfiguration];
        }
    }
    
    @end

    1.2 AVFoundation框架扫描二维码的功能封装
    上面是系统自带的二维码扫描的基本功能实现,下面我们来实现一下在实际开发中二维码扫描的实际效果,不过就是添加了一条扫描的线条。
    示例代码:
    Scan2CodeViewController.h

    #import <UIKit/UIKit.h>
    
    @protocol ScanImageViewDelegate<NSObject>
    
    - (void)reportScanResult:(NSString *)result;
    
    @end
    
    @interface Scan2CodeViewController : UIViewController
    
    @property (nonatomic,weak)id <ScanImageViewDelegate>delegate;//代理方法传递数据
    
    @end
    示例代码:
    Scan2CodeViewController.m
    #import "Scan2CodeViewController.h"
    #import <AVFoundation/AVFoundation.h>
    
    #define SCANVIEW_EdgeTop 70.0
    #define SCANVIEW_EdgeLeft 50.0
    #define TINTCOLOR_ALPHA 0.2 //浅色透明度
    #define DARKCOLOR_ALPHA 0.3 //深色透明度
    #define VIEW_WIDTH [UIScreen mainScreen].bounds.size.width
    #define VIEW_HEIGHT [UIScreen mainScreen].bounds.size.height
    
    static const char *kScanQRCodeQueueName = "ScanQRCodeQueue";
    @interface Scan2CodeViewController () <AVCaptureMetadataOutputObjectsDelegate>{
        //设置扫描画面
        UIView *_scanView;
        NSTimer *_timer;
    
        UIView *_QrCodeline;
        UIView *_QrCodeline1;
        UIImageView *_scanCropView;//扫描窗口
        UIButton *_lightButton;//灯光按钮
        AVCaptureSession *_captureSession;
        AVCaptureVideoPreviewLayer *_videoPreviewLayer;
    }
    
    @end
    
    @implementation Scan2CodeViewController
    
    - (void)viewWillDisappear:(BOOL)animated
    {
        [super viewWillDisappear:animated];
    
        [self stopTimer];
    }
    
    - (void)viewDidLoad {
        [super viewDidLoad];
        //初始化扫描界面
        [self setScanView];
    
        // 开始扫描
        [self startReading];
    
        //启动定时器
        [self createTimer];
    }
    
    - (BOOL)startReading
    {
        // 获取 AVCaptureDevice 实例
        NSError * error;
        AVCaptureDevice *captureDevice = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
        // 初始化输入流
        AVCaptureDeviceInput *input = [AVCaptureDeviceInput deviceInputWithDevice:captureDevice error:&error];
        if (!input) {
            NSLog(@"%@", [error localizedDescription]);
            return NO;
        }
        // 创建会话
        _captureSession = [[AVCaptureSession alloc] init];
        //提高图片质量为1080P,提高识别效果
        _captureSession.sessionPreset = AVCaptureSessionPreset1920x1080;
        // 添加输入流
        [_captureSession addInput:input];
        // 初始化输出流
        AVCaptureMetadataOutput *captureMetadataOutput = [[AVCaptureMetadataOutput alloc] init];
    
        //设置扫描范围
        captureMetadataOutput.rectOfInterest =CGRectMake((_scanCropView.frame.origin.y-10)/VIEW_HEIGHT, (_scanCropView.frame.origin.x-10)/VIEW_WIDTH, (_scanCropView.frame.size.width+10)/VIEW_HEIGHT, (_scanCropView.frame.size.height+10)/VIEW_WIDTH);
    
        // 添加输出流
        [_captureSession addOutput:captureMetadataOutput];
    
        // 创建dispatch queue.
        dispatch_queue_t dispatchQueue;
        dispatchQueue = dispatch_queue_create(kScanQRCodeQueueName, NULL);
        [captureMetadataOutput setMetadataObjectsDelegate:self queue:dispatchQueue];
        // 设置元数据类型 AVMetadataObjectTypeQRCode
        [captureMetadataOutput setMetadataObjectTypes:[NSArray arrayWithObject:AVMetadataObjectTypeQRCode]];
    
        // 创建输出对象
        _videoPreviewLayer = [[AVCaptureVideoPreviewLayer alloc] initWithSession:_captureSession];
        [_videoPreviewLayer setVideoGravity:AVLayerVideoGravityResizeAspectFill];
    
        [_videoPreviewLayer setFrame:_scanView.layer.bounds];
        [_scanView.layer insertSublayer:_videoPreviewLayer atIndex:0];
        // 开始会话
        [_captureSession startRunning];
    
        return YES;
    }
    
    - (void)stopReading
    {
        // 停止会话
        [_captureSession stopRunning];
        _captureSession = nil;
    }
    
    #pragma mark -
    #pragma mark - AVCaptureMetadataOutputObjectsDelegate
    -(void)captureOutput:(AVCaptureOutput *)captureOutput didOutputMetadataObjects:(NSArray *)metadataObjects
          fromConnection:(AVCaptureConnection *)connection
    {
        if (metadataObjects != nil && [metadataObjects count] > 0) {
            AVMetadataMachineReadableCodeObject *metadataObj = [metadataObjects objectAtIndex:0];
            NSString *result;
            if ([[metadataObj type] isEqualToString:AVMetadataObjectTypeQRCode]) {
                result = metadataObj.stringValue;
            } else {
                NSLog(@"不是二维码");
            }
            //调用代理对象的协议方法来实现数据传递
            [self dismissViewControllerAnimated:YES completion:nil];
            dispatch_async(dispatch_get_main_queue(), ^{
                if ([self.delegate respondsToSelector:@selector(reportScanResult:)]) {
                    [self.delegate reportScanResult:result];
                }
            });
            [self stopReading];
        }
        return;
    }
    - (void)createTimer
    {
        _timer=[NSTimer scheduledTimerWithTimeInterval:2.2 target:self selector:@selector(moveUpAndDownLine) userInfo:nil repeats:YES];
    }
    - (void)stopTimer
    {
        if ([_timer isValid] == YES) {
            [_timer invalidate];
            _timer = nil;
        }
    
    }
    
    // 二维码的扫描区域
    - (void)setScanView
    {
        _scanView=[[UIView alloc] initWithFrame:CGRectMake(0,0, VIEW_WIDTH,VIEW_HEIGHT )];
        _scanView.backgroundColor=[UIColor clearColor];
        [self.view addSubview:_scanView];
    
        //最上部view
        UIView *upView = [[UIView alloc] initWithFrame:CGRectMake(0,0, VIEW_WIDTH,SCANVIEW_EdgeTop)];
        upView.alpha =TINTCOLOR_ALPHA;
        upView.backgroundColor = [UIColor blackColor];
        [_scanView addSubview:upView];
    
        //左侧的view
        UIView *leftView = [[UIView alloc] initWithFrame:CGRectMake(0, SCANVIEW_EdgeTop, SCANVIEW_EdgeLeft,VIEW_WIDTH - 2 * SCANVIEW_EdgeLeft)];
        leftView.alpha =TINTCOLOR_ALPHA;
        leftView.backgroundColor = [UIColor blackColor];
        [_scanView addSubview:leftView];
    
        // 中间扫描区
        _scanCropView=[[UIImageView alloc] initWithFrame:CGRectMake(SCANVIEW_EdgeLeft,SCANVIEW_EdgeTop, VIEW_WIDTH - 2 * SCANVIEW_EdgeLeft, VIEW_WIDTH - 2 * SCANVIEW_EdgeLeft)];
        //scanCropView.image=[UIImage imageNamed:@""];
        _scanCropView.layer.borderColor=[UIColor greenColor].CGColor;
        _scanCropView.layer.borderWidth=2.0;
        _scanCropView.backgroundColor=[UIColor clearColor];
        [_scanView addSubview:_scanCropView];
    
        //右侧的view
        UIView *rightView = [[UIView alloc] initWithFrame:CGRectMake(VIEW_WIDTH - SCANVIEW_EdgeLeft,SCANVIEW_EdgeTop, SCANVIEW_EdgeLeft, VIEW_WIDTH - 2 * SCANVIEW_EdgeLeft)];
        rightView.alpha =TINTCOLOR_ALPHA;
        rightView.backgroundColor = [UIColor blackColor];
        [_scanView addSubview:rightView];
    
        //底部view
        UIView *downView = [[UIView alloc] initWithFrame:CGRectMake(0, VIEW_WIDTH - 2 * SCANVIEW_EdgeLeft + SCANVIEW_EdgeTop, VIEW_WIDTH, VIEW_HEIGHT - (VIEW_WIDTH - 2 * SCANVIEW_EdgeLeft + SCANVIEW_EdgeTop))];
        //downView.alpha = TINTCOLOR_ALPHA;
        downView.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:TINTCOLOR_ALPHA];
        [_scanView addSubview:downView];
    
        //用于说明的label
        UILabel *labIntroudction= [[UILabel alloc] init];
        labIntroudction.backgroundColor = [UIColor clearColor];
        labIntroudction.frame=CGRectMake(0,5, VIEW_WIDTH,20);
        labIntroudction.numberOfLines=1;
        labIntroudction.font=[UIFont systemFontOfSize:15.0];
        labIntroudction.textAlignment=NSTextAlignmentCenter;
        labIntroudction.textColor=[UIColor whiteColor];
        labIntroudction.text=@"将二维码对准方框,即可自动扫描";
        [downView addSubview:labIntroudction];
    
        //取消button
        UIButton *cancelButton = [UIButton buttonWithType:UIButtonTypeCustom];
        cancelButton.backgroundColor =[[UIColor blackColor] colorWithAlphaComponent:DARKCOLOR_ALPHA];
        cancelButton.frame =CGRectMake(0, 90, VIEW_WIDTH, 40);
        cancelButton.titleLabel.font =[UIFont systemFontOfSize:15.0];
        cancelButton.titleLabel.textAlignment = NSTextAlignmentCenter;
        [cancelButton setTitle:@"取消" forState:UIControlStateNormal];
        [cancelButton addTarget:self action:@selector(cancelAction) forControlEvents:UIControlEventTouchUpInside];
        [downView addSubview:cancelButton];
    
        //用于开关灯操作的button
        _lightButton = [UIButton buttonWithType:UIButtonTypeCustom];
        _lightButton.frame =CGRectMake(0, 40, VIEW_WIDTH, 40);
        [_lightButton setTitle:@"开启闪光灯" forState:UIControlStateNormal];
        [_lightButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        _lightButton.backgroundColor =[[UIColor blackColor] colorWithAlphaComponent:DARKCOLOR_ALPHA];
        _lightButton.titleLabel.textAlignment=NSTextAlignmentCenter;
        _lightButton.titleLabel.font=[UIFont systemFontOfSize:15.0];
        [_lightButton addTarget:self action:@selector(openLight) forControlEvents:UIControlEventTouchUpInside];
        [downView addSubview:_lightButton];
    
        //画中间的基准线
        _QrCodeline = [[UIView alloc] initWithFrame:CGRectMake(SCANVIEW_EdgeLeft, SCANVIEW_EdgeTop, VIEW_WIDTH- 2 * SCANVIEW_EdgeLeft, 2)];
        _QrCodeline.backgroundColor = [UIColor greenColor];
        [_scanView addSubview:_QrCodeline];
    
        //画中间的基准线
        _QrCodeline1 = [[UIView alloc] initWithFrame:CGRectMake(SCANVIEW_EdgeLeft, SCANVIEW_EdgeTop, VIEW_WIDTH- 2 * SCANVIEW_EdgeLeft, 2)];
        _QrCodeline1.backgroundColor = [UIColor greenColor];
        [_scanView addSubview:_QrCodeline1];
    
        // 先让第二根线运动一次,避免定时器执行的时差,让用户感到启动App后,横线就开始移动
        [UIView animateWithDuration:2.2 animations:^{
    
            _QrCodeline1.frame = CGRectMake(SCANVIEW_EdgeLeft, VIEW_WIDTH - 2 * SCANVIEW_EdgeLeft + SCANVIEW_EdgeTop - 2, VIEW_WIDTH - 2 * SCANVIEW_EdgeLeft, 1);
        }];
    
    
    }
    
    // 当地一根线到达底部时,第二根线开始下落运动,此时第一根线已经在顶部,当第一根线接着下落时,第二根线到达顶部.依次循环
    - (void)moveUpAndDownLine
    {
        CGFloat Y = _QrCodeline.frame.origin.y;
        if (Y == SCANVIEW_EdgeTop) {
            [UIView animateWithDuration:2.2 animations:^{
    
                _QrCodeline.frame = CGRectMake(SCANVIEW_EdgeLeft, VIEW_WIDTH - 2 * SCANVIEW_EdgeLeft + SCANVIEW_EdgeTop - 2, VIEW_WIDTH - 2 * SCANVIEW_EdgeLeft, 1);
            }];
            _QrCodeline1.frame = CGRectMake(SCANVIEW_EdgeLeft, SCANVIEW_EdgeTop, VIEW_WIDTH - 2 * SCANVIEW_EdgeLeft, 1);
        }
        else if (Y == VIEW_WIDTH - 2 * SCANVIEW_EdgeLeft + SCANVIEW_EdgeTop - 2) {
            _QrCodeline.frame = CGRectMake(SCANVIEW_EdgeLeft, SCANVIEW_EdgeTop, VIEW_WIDTH - 2 * SCANVIEW_EdgeLeft, 1);
            [UIView animateWithDuration:2.2 animations:^{
    
                _QrCodeline1.frame = CGRectMake(SCANVIEW_EdgeLeft, VIEW_WIDTH - 2 * SCANVIEW_EdgeLeft + SCANVIEW_EdgeTop - 2, VIEW_WIDTH - 2 * SCANVIEW_EdgeLeft, 1);
            }];
        }
    
    }
    
    //照明灯光
    -(void)openLight{
        if ([_lightButton.titleLabel.text isEqualToString:@"开启闪光灯"]) {
            [self systemLightSwitch:YES];
        } else {
            [self systemLightSwitch:NO];
        }
    }
    
    - (void)systemLightSwitch:(BOOL)open
    {
        if (open) {
            [_lightButton setTitle:@"关闭闪光灯" forState:UIControlStateNormal];
        } else {
            [_lightButton setTitle:@"开启闪光灯" forState:UIControlStateNormal];
        }
        AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
        if ([device hasTorch]) {
            [device lockForConfiguration:nil];
            if (open) {
                [device setTorchMode:AVCaptureTorchModeOn];
            } else {
                [device setTorchMode:AVCaptureTorchModeOff];
            }
            [device unlockForConfiguration];
        }
    }
    
    // 取消button
    - (void)cancelAction{
        [self dismissViewControllerAnimated:YES completion:nil];
    }
    
    @end

    2. 使用ZBarSDK识别二维码

       在iOS7.0以前,大部分应用识别二维码都是通过第三方库来实现的。事实上,在主流APP中二维码/条形码的作用主要分三种表现形式来集成:
    
    • 调用手机摄像头并打开系统照相机全屏去拍摄。
    • 自定义照相机视图的frame,自己控制并添加相关扫码指南。
    • 识别相册图片中的二维码图片。

      首先我们先来看一下如何集成ZBarSDK:
      第一步:将 ZBarSDK导入到工程,并集成相关的框架,

    • AVFoundation.framework
    • CoreMedia.framework
    • CoreVideo.framework
    • QuartzCore.framework
    • libiconv.dylib
      如下图:
      这里写图片描述
      第二步:关闭代码优化
      导入相关框架后,系统编译仍然不通过,提示的错误如下:
      这里写图片描述
      这是由于系统代码优化产生的错误,将Xcode的bitcode选项设置为No就可以通过编译了。
      这里写图片描述

      第三步:导入头文件,初始化ZBar相机控制器,并实现相关代理;

    • 调用系统相机全屏拍摄,使用ZBarReaderViewController,并声明协议。
    • 自定义扫描窗口,使用ZBarReaderView,并声明协议。
    • 识别相册的二维码图片,使用ZBarReaderController,并声明

    2.1 调用系统相机:

    示例代码:

    #import "ViewController.h"
    #import "ZBarSDK.h"
    
    @interface ViewController ()<ZBarReaderDelegate>
    
    @end
    
    @implementation ViewController
    
    - (void)viewDidLoad {
        [super viewDidLoad];
    }
    
    - (IBAction)systemCamara:(id)sender {
    
        // 初始化扫码视图控制器
        ZBarReaderViewController *reader = [ZBarReaderViewController new];
    
        // 设置代理
        reader.readerDelegate = self;
        // 设置识别类型
        ZBarImageScanner *scanner = reader.scanner;
        [scanner setSymbology:ZBAR_I25
                       config:ZBAR_CFG_ENABLE
                           to:0];
        reader.showsZBarControls = YES;
    
        // 推出扫码视图控制器
        [self presentViewController:reader animated:YES completion:nil];
    
    }
    
    - (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info {
    
        id results = [info objectForKey:ZBarReaderControllerResults];
        ZBarSymbol * symbol;
        for(symbol in results) {
    
            NSString *result = symbol.data;
            NSLog(@"%@",result);
        }
    
        // 退出拍照界面
        [picker dismissViewControllerAnimated:YES completion:nil];
    
    }
    
    @end

    注释:
    直接调用系统相机来实现二维码扫描虽然简单,但是存在极大的问题,那就是这样只能做全屏扫描,不能自定义二维码扫描的选取框。

    2.2 自定义扫描窗口

    项目中实现的二维码扫描功能我们发现都是可以设置扫描范围内的,下面我们来看一下如何自定义扫描的窗口。
    

    示例代码:

    #import "ViewController.h"
    #import "ZBarSDK.h"
    
    @interface ViewController ()<ZBarReaderViewDelegate>
    
    @end
    
    @implementation ViewController
    
    - (void)viewDidLoad {
        [super viewDidLoad];
    }
    
    #pragma mark -
    #pragma mark - 自定义扫描窗口
    - (IBAction)scan2Code:(id)sender {
    
        // 初始化扫描窗口
        ZBarReaderView *readerView = [[ZBarReaderView alloc] init];
    
        // 自定义大小
        readerView.frame = CGRectMake(self.view.frame.size.width/2-100, self.view.frame.size.height/2-100, 200, 200);
    
        // 设置代理
        readerView.readerDelegate = self;
    
        // 添加到父视图
        [self.view addSubview:readerView];
    
        // 二维码识别设置
        ZBarImageScanner *scanner = readerView.scanner;
        [scanner setSymbology:ZBAR_I25
                       config:ZBAR_CFG_ENABLE
                           to:0];
    
        // 开始扫描
        [readerView start];
    
    }
    
    #pragma mark - ZBarReaderViewDelegate
    - (void)readerView:(ZBarReaderView *)readerView didReadSymbols:(ZBarSymbolSet *)symbols fromImage:(UIImage *)image {
    
        // 获取扫描的标识
        ZBarSymbol *symbol = nil;
        for (symbol in symbols) {
    
            NSString *result = symbol.data;
    
            NSLog(@"%@",result);
        }
        // 停止扫描
        [readerView stop];
    }
    
    @end

    2.3 识别相册中的二维码图片:

    使用ZBarSDK可以直接选中相册中的二维码图片进行识别,这是系统自带的识别功能所不具备的。下面是识别相册中的二维码图片的实现方法。
    

    示例代码:

    #import "ViewController.h"
    #import "ZBarSDK.h"
    
    @interface ViewController ()<UIImagePickerControllerDelegate,UINavigationControllerDelegate>
    
    @end
    
    @implementation ViewController
    
    - (void)viewDidLoad {
        [super viewDidLoad];
    }
    
    // 识别相册图片中的二维码
    - (IBAction)pick2Code:(id)sender {
    
        // 进入相册选中相册中的二维码图片
        UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
        imagePicker.sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;// 图片来源为相册
        imagePicker.delegate = self;
    
        // 进入相册
        [self presentViewController:imagePicker animated:YES completion:nil];
    
    }
    
    #pragma mark -
    #pragma mark - UIImagePickerControllerDelegate
    // 选中图片后调用该方法
    - (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info {
    
        // 获取选中的图片
        UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
        CGImageRef cgImage = image.CGImage;
    
        ZBarReaderController *reader = [[ZBarReaderController alloc] init];
        reader.delegate = self;
        ZBarSymbol *symbol = nil;
        for (symbol in [reader scanImage:cgImage]) {
    
            NSString *resulot = symbol.data;
            NSLog(@"%@",resulot);
        }
    
        // 识别结束后返回主界面
        [picker dismissViewControllerAnimated:YES completion:nil];
    }
    
    @end
    展开全文
  • 这两天,在弄一个二维码扫描的东西。 二维码为移动设备购物提供了方便。在电商行业也有一些商家开始正式商业应用,我所知道的 1号店就在使用这种东西。 一个二维码对应一个产品。 二维码可以使用Google提供的...
  • Zxing二维码扫描Demo完整源码下载

    热门讨论 2017-04-10 20:54:37
    集成Zxing二维码扫描,可从相册选择图片扫描、开启闪光灯、生成二维码图片功能
  • ubuntu安装zbar二维码扫描

    千次阅读 2017-03-02 11:34:04
    安装 ImageMagick : $sudo apt- get install imagemagick libmagickwand-dev 3 执行时出错 zbarcam: error while loading shared libraries: libzbar.so .0 : cannot open shared object file: No ...
  • 二维码扫描实现

    千次阅读 2017-05-03 16:06:24
    二维码扫描实现二维码原理 三个回形大方块,是为了给相机定位的;中间的黑白块,黑块代表1,白块代表0,八个一组,组成二进制信息。二维码原理 这个小视频,简单的介绍了下二维码iOS简单的实现二维码扫描知道二维码...
  • Android二维码扫描Demo 程序源码

    万次下载 热门讨论 2013-08-08 08:24:25
    此为示例代码,详细讲解请参考: http://blog.csdn.net/guolin_blog/article/details/9526247
  • Swift3.0二维码(QRCODE)扫描实现(写一个仿支付宝二维码扫描的效果)
  • Android二维码扫描

    千次阅读 2016-04-29 17:36:55
    本文详细说明怎么在Android端实现二维码扫描,只是讲述如何利用Google zxing进行二维码扫描,不涉及代码的深入研究,结果文章最后附有demo,demo可直接使用,觉得文章累赘可以直接拷demo中的包和类应用到自己的项目...
  • mui实现二维码扫描

    千次阅读 2017-04-06 15:41:26
    mui实现二维码扫描 直接上代码 发现 物品二维码扫描
  • Android二维码扫描、生成

    千次阅读 2015-12-31 11:59:20
    Android二维码扫描、生成 现在使用二维码作为信息的载体已经越来越普及,那么二维码的生成以及扫描是如何实现的呢 google为我们提供了zxing开源库供我们使用 zxing GitHub源码地址 But!But!But!仅仅是源码!...
  • Mui二维码扫描

    千次阅读 2017-11-28 17:50:25
    最近的项目需要扫二维码或者条形码实现自动搜索,经过漫长的研究,后来发现MUI已经封装了二维码,以及条形码扫描...如果直接在chrome打开,点击二维码扫描,此时会报错'plus is not defined',这是因为普通浏览器里没
  • 一个二维码扫描自动识别下载应用,看到过一些二维码,用安卓手机扫直接下载akp,用苹果手机扫跳转至appstore。这是如何实现的?
  • 微信二维码扫描下载APK

    千次阅读 2015-04-30 08:45:50
    前几天给客户制作的app需要上线,生成二维码扫描进行下载,把生成好的apk挂在服务器端,将地址复制下来,通过草料二维码(http://cli.im/)生成一个二维码  也许你会看到有个app的选项,为什么不选择app呢。点开...
  • android_zbar二维码扫描

    千次下载 热门讨论 2014-08-13 10:27:52
    zbar二维码扫描 解决了中文乱码 有人说我上次传的分太高,我索性就不要分了。 这是博文 http://blog.csdn.net/nie312122330/article/details/38314977
  • Android之条码扫描二维码扫描

    千次阅读 2013-07-26 16:58:17
    Android之条码扫描二维码扫描  二维码条形码扫描,参考技术网址:  1.Apache License 2.0 开源的 ZXing项目的简化版 http://xinlanzero.iteye.com/blog/1114826 (作者的项目中的缺少core.jar,需...
  • 二维码扫描+长按识别二维码demo

    千次阅读 2017-03-29 10:23:36
    二维码扫描+长按识别二维码demo,已封装好 源码下载
  • 二维码扫描下载APP plist文件配置 不知为什么我直接写代码 上传不上来 不显示 所以只能发图了 高手指点一下。
  • Hbuilder 二维码扫描 第一次可以正常扫描 第二次不重新加载窗体!
  • iOS原生二维码扫描&libqrencode生成二维码
  • 使用ZXing实现二维码扫描

    万次阅读 2016-12-21 14:32:21
     其中刘超大神使用ZXing写了一个快速集成二维码扫描的工具类,实现其核心的实现扫描的功能。使用时通过调用二维码工具类,几行代码就可以实现二维码扫描的功能。  参考资料:   二维码工具类下载地址: ...
  • 完整的二维码扫描解决方案

    千次阅读 2018-04-24 12:06:40
    现在的应用都有自己的二维码扫描工具,最近接手的项目也不例外,集成了ZXing二维码扫描,但是用起来却实在差强人意,后来看到QrCodeReaderView效果不错,识别速度上有明显提高,而且使用也非常简单,于是便迅速集成...

空空如也

空空如也

1 2 3 4 5 ... 20
收藏数 129,723
精华内容 51,889
关键字:

下载安装二维码扫描