Android实战_Zxing实现扫描功能

来源:互联网 发布:python 图论库 编辑:程序博客网 时间:2024/06/05 09:47

前言

本篇文章从初学者的角度出发,从一个不知道对二维码扫描怎么下手的工作者,需要一个简单的扫描功能的话,可以阅读该篇文章。作为Google开源框架Zxing,里面的文件很大,这里主要讲的是精简ZXing项目后只保留扫描功能的代码,可以缩小项目的大小,对于只要扫描功能的项目已经够用了。扫描后的结果,只要通过WebView百度一下就出来了。简单的说,可以把Zxing这个二维码扫描功能当做一个第三方服务来使用,本篇文章分为两部分,Zxing的集成和Zxing的使用



第一部分:Zxing的集成

步骤一:下载我们所需要的Zxing精简版,在Github上搜索Zxing,看到这条记录 把它下载并导入工程,修改报错

步骤二:还有些类报错,说明是jar包没有引入,接下来引入jar包



第二部分:Zxing的使用


步骤一:在manifests中声明权限和Activity(参照例子)

步骤二:在代码中启动我们的二维码扫描页面(使用CaptureActivity


步骤三:如果你想对Capture页面的界面进行修改可以制作一张图片替换drawable里面图片,这里我们只介绍对读取结果的介绍,我们打开ResultActivity文件:


public class ResultActivity extends Activity {    private ImageView mResultImage;    private TextView mResultText;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_result);        Bundle extras = getIntent().getExtras();        mResultImage = (ImageView) findViewById(R.id.result_image);        mResultText = (TextView) findViewById(R.id.result_text);        if (null != extras) {            int width = extras.getInt("width");            int height = extras.getInt("height");            LayoutParams lps = new LayoutParams(width, height);            lps.topMargin = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 30, getResources().getDisplayMetrics());            lps.leftMargin = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 20, getResources().getDisplayMetrics());            lps.rightMargin = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 20, getResources().getDisplayMetrics());                        mResultImage.setLayoutParams(lps);            String result = extras.getString("result");            mResultText.setText(result);            Bitmap barcode = null;            byte[] compressedBitmap = extras.getByteArray(DecodeThread.BARCODE_BITMAP);            if (compressedBitmap != null) {                barcode = BitmapFactory.decodeByteArray(compressedBitmap, 0, compressedBitmap.length, null);                // Mutable copy:                barcode = barcode.copy(Bitmap.Config.RGB_565, true);            }            mResultImage.setImageBitmap(barcode);        }    }}



我们大致可以明白,从CaptureActivity中传来一个Bundle的参数,并解析Bundle的宽和高,将其交给ImageView的参数,做为宽高,同时增加Margin属性,同时解析一个Byte数组,其中就是图片的文件的字节码,其中解析的result,则是我们需要的二维码结果:

String result = extras.getString("result");mResultText.setText(result);



项目地址:

0 0