zxing的github地址为:[https://github.com/zxing/zxing](https://github.com/zxing/zxing)
因为使用过程需要编译(或者拷贝源文件),稍微麻烦一些,所以采用了另外一个封装版本:[https://github.com/yipianfengye/android-zxingLibrary](https://github.com/yipianfengye/android-zxingLibrary)
#### 初始化
在项目入口(比如Application的onCreate方法)初始化
~~~
ZXingLibrary.initDisplayOpinion(this);
~~~
#### 定义组件
随便定义一个ImageView,其中backgroud已经设置了二维码图片。
~~~
ImageView imageview = (ImageView) findViewById(R.id.imageview);
~~~
#### 公共方法
改方法实现了将bitmap识别出文字的功能。
~~~
public Result parsePic(Bitmap bitmap) {
// 解析转换类型UTF-8
Hashtable<DecodeHintType, String> hints = new Hashtable<DecodeHintType, String>();
hints.put(DecodeHintType.CHARACTER_SET, "utf-8");
// 新建一个RGBLuminanceSource对象,将bitmap图片传给此对象
int lWidth = bitmap.getWidth();
int lHeight = bitmap.getHeight();
int[] lPixels = new int[lWidth * lHeight];
bitmap.getPixels(lPixels, 0, lWidth, 0, 0, lWidth, lHeight);
RGBLuminanceSource rgbLuminanceSource = new RGBLuminanceSource(lWidth,
lHeight, lPixels);
// 将图片转换成二进制图片
BinaryBitmap binaryBitmap = new BinaryBitmap(new HybridBinarizer(
rgbLuminanceSource));
// 初始化解析对象
QRCodeReader reader = new QRCodeReader();
// 开始解析
Result result = null;
try {
result = reader.decode(binaryBitmap, hints);
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
~~~
#### 长按事件
有了上面的方法,只需要将ImageView转化为bitmap就行了。
~~~
imageView.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View arg0) {
Bitmap bitmap = ((BitmapDrawable)imageView.getDrawable()).getBitmap();
Result ret = parsePic(bitmap);
if (null == ret) {
Toast.makeText(MainActivity.this, "解析结果:null",
Toast.LENGTH_LONG).show();
} else {
Toast.makeText(MainActivity.this,
"解析结果:" + ret.toString(), Toast.LENGTH_LONG).show();
}
return false;
}
});
~~~