Android集成zxing扫码框架功能
程序员文章站
2022-06-03 13:06:14
我们知道zxing是一个强大的处理二维码和条形码等的开源库,本篇文章记录一下自己在项目中集成zxing开源库的过程。导入依赖implementation 'com.google.zxing:core:...
我们知道zxing是一个强大的处理二维码和条形码等的开源库,本篇文章记录一下自己在项目中集成zxing开源库的过程。
导入依赖
implementation 'com.google.zxing:core:3.3.3'
申请权限
在androidmanifest中申请相应权限:
<!--相机--> <uses-permission android:name="android.permission.camera" /> <!--震动--> <uses-permission android:name="android.permission.vibrate" /> <!--存储--> <uses-permission android:name="android.permission.write_external_storage" /> <uses-permission android:name="android.permission.read_external_storage" />
导入相关代码和资源文件
导入的代码文件如下(源码在末尾):
相关的资源文件:
1、在res/values下新建ids.xml文件,引入下面id:
<!--二维码/条形码扫描相关--> <item name="auto_focus" type="id" /> <item name="decode" type="id" /> <item name="decode_failed" type="id" /> <item name="decode_succeeded" type="id" /> <item name="encode_failed" type="id" /> <item name="encode_succeeded" type="id" /> <item name="launch_product_query" type="id" /> <item name="quit" type="id" /> <item name="restart_preview" type="id" /> <item name="return_scan_result" type="id" /> <item name="search_book_contents_failed" type="id" /> <item name="search_book_contents_succeeded" type="id" />
2、在res/values下新建attrs.xml文件,加入扫码框的属性,主要是viewfinderview在使用:
<!--扫码框属性--> <declare-styleable name="viewfinderview"> <attr name="corner_color" format="color" /> <attr name="corner_size" format="dimension" /> <attr name="corner_stroke_width" format="dimension" /> <attr name="corner_position" format="enum"> <enum name="inside" value="1" /> <enum name="outside" value="2" /> </attr> <attr name="line_color" format="color" /> <attr name="line_height" format="dimension" /> <attr name="line_move_distance" format="dimension" /> <attr name="frame_width" format="dimension" /> <attr name="frame_height" format="dimension" /> <attr name="frame_centerx" format="dimension" /> <attr name="frame_centery" format="dimension" /> <attr name="frame_color" format="color" /> <attr name="frame_stroke_width" format="dimension" /> <attr name="mask_color" format="color" /> <attr name="result_point_color" format="color" /> <attr name="label_text" format="string" /> <attr name="label_text_color" format="color" /> <attr name="label_text_size" format="dimension" /> <attr name="label_text_margin" format="dimension" /> </declare-styleable>
3、在res下新建raw目录,导入beep.mp3,实现扫码成功的滴滴音效,beepmanager在使用
上面是一些比较重要的资源。
然后介绍一下几个主要的类:
1、viewfinderview:自定义扫描框,代码如下,因为有注释,就不多说明了。
public final class viewfinderview extends view { private static final long animation_delay = 10l; private static final int opaque = 1; private static final int corner_inside = 1; //四个边角在扫描区内 private static final int corner_outside = 2; //四个边角在扫描区外 private paint paint; //扫描区四个边角的颜色 private int cornercolor; //扫描区边角的大小 private float cornersize; //扫描区边角的宽度 private float cornerstrokewidth; //边角的方向,在扫描区域内还是扫描区域外 private int cornerposition; //扫描线颜色 private int linecolor; //扫描线高度 private float lineheight; //扫描线移动距离 private float linemovedistance; //扫描区域宽度度 private float framewidth; //扫描区域高度 private float frameheight; //扫描区域中心位置的x坐标,默认正中间,在onlayout中设置 private float framecenterx; //扫描区域中心位置的y坐标,默认正中间,在onlayout中设置 private float framecentery; //扫描区域边框颜色 private int framecolor; //扫描区域边框宽度 private float framestrokewidth; //模糊区域颜色 private int maskcolor; //扫描点的颜色 private int resultpointcolor; //扫描区域提示文本 private string labeltext; //扫描区域提示文本颜色 private int labeltextcolor; //扫描区域提示文本字体大小 private float labeltextsize; //扫描区域提示文本的边距 private float labeltextmargin; public static int scannerstart = 0; public static int scannerend = 0; private collection<resultpoint> possibleresultpoints; private collection<resultpoint> lastpossibleresultpoints; // this constructor is used when the class is built from an xml resource. public viewfinderview(context context, attributeset attrs) { super(context, attrs); //初始化自定义属性信息 typedarray ta = context.obtainstyledattributes(attrs, r.styleable.viewfinderview); cornercolor = ta.getcolor(r.styleable.viewfinderview_corner_color, getresources().getcolor(r.color.colorprimary)); cornersize = ta.getdimension(r.styleable.viewfinderview_corner_size, dp2px(context, 28)); cornerstrokewidth = ta.getdimension(r.styleable.viewfinderview_corner_stroke_width, dp2px(context, 4)); cornerposition = ta.getint(r.styleable.viewfinderview_corner_position, corner_inside); linecolor = ta.getcolor(r.styleable.viewfinderview_line_color, getresources().getcolor(r.color.colorprimary)); lineheight = ta.getdimension(r.styleable.viewfinderview_line_height, dp2px(context, 3)); linemovedistance = ta.getdimension(r.styleable.viewfinderview_line_move_distance, dp2px(context, 2)); framewidth = ta.getdimension(r.styleable.viewfinderview_frame_width, dp2px(context, 220)); frameheight = ta.getdimension(r.styleable.viewfinderview_frame_height, dp2px(context, 220)); framecenterx = ta.getdimension(r.styleable.viewfinderview_frame_centerx, -1); framecentery = ta.getdimension(r.styleable.viewfinderview_frame_centery, -1); framecolor = ta.getcolor(r.styleable.viewfinderview_frame_color, color.parsecolor("#90ffffff")); framestrokewidth = ta.getdimension(r.styleable.viewfinderview_frame_stroke_width, dp2px(context, 0.2f)); maskcolor = ta.getcolor(r.styleable.viewfinderview_mask_color, color.parsecolor("#60000000")); resultpointcolor = ta.getcolor(r.styleable.viewfinderview_result_point_color, color.transparent); labeltext = ta.getstring(r.styleable.viewfinderview_label_text); labeltextcolor = ta.getcolor(r.styleable.viewfinderview_label_text_color, color.white); labeltextsize = ta.getdimension(r.styleable.viewfinderview_label_text_size, sp2px(context, 15)); labeltextmargin = ta.getdimension(r.styleable.viewfinderview_label_text_margin, dp2px(context, 18)); ta.recycle(); paint = new paint(); paint.setantialias(true); possibleresultpoints = new hashset<resultpoint>(5); } @override protected void onlayout(boolean changed, int left, int top, int right, int bottom) { super.onlayout(changed, left, top, right, bottom); //如果没有设置framecenterx和framecentery默认布局正中间的x、y坐标 framecenterx = (framecenterx == -1) ? getwidth() / 2f : framecenterx; framecentery = (framecentery == -1) ? getheight() / 2f : framecentery; //设置扫描区域位置 int leftoffset = (int) (framecenterx - framewidth / 2f); int topoffset = (int) (framecentery - frameheight / 2f); //设置扫描区不超过屏幕 leftoffset = leftoffset > 0 ? leftoffset : 0; topoffset = topoffset > 0 ? topoffset : 0; rect rect = new rect(); rect.left = leftoffset; rect.top = topoffset; rect.right = (int) (leftoffset + framewidth); rect.bottom = (int) (topoffset + frameheight); cameramanager.get().setframingrect(rect); } @override public void ondraw(canvas canvas) { rect frame = cameramanager.get().getframingrect(); if (frame == null) { return; } if (scannerstart == 0 || scannerend == 0) { scannerstart = frame.top; scannerend = frame.bottom; } int width = canvas.getwidth(); int height = canvas.getheight(); //绘制模糊区域 drawexterior(canvas, frame, width, height); //绘制扫描区边框 drawframe(canvas, frame); //绘制边角 drawcorner(canvas, frame); //绘制提示信息 drawtextinfo(canvas, frame); //绘制扫描线 drawscanline(canvas, frame); //绘制闪烁点 drawresultpoint(canvas, frame); // request another update at the animation interval, but only repaint the laser line, // not the entire viewfinder mask. //指定重绘区域,该方法会在子线程中执行 postinvalidatedelayed(animation_delay, frame.left, frame.top, frame.right, frame.bottom); } // 绘制模糊区域 draw the exterior (i.e. outside the framing rect) darkened private void drawexterior(canvas canvas, rect frame, int width, int height) { paint.setcolor(maskcolor); canvas.drawrect(0, 0, width, frame.top, paint); canvas.drawrect(0, frame.top, frame.left, frame.bottom, paint); canvas.drawrect(frame.right, frame.top, width, frame.bottom, paint); canvas.drawrect(0, frame.bottom, width, height, paint); } // 绘制扫描区边框 draw a two pixel solid black border inside the framing rect private void drawframe(canvas canvas, rect frame) { if (framestrokewidth > 0) { paint.setcolor(framecolor); if (cornerposition == corner_inside) { //边角在扫描区内 //左边 canvas.drawrect(frame.left, frame.top, frame.left + framestrokewidth, frame.bottom, paint); //上边 canvas.drawrect(frame.left, frame.top, frame.right, frame.top + framestrokewidth, paint); //右边 canvas.drawrect(frame.right - framestrokewidth, frame.top, frame.right, frame.bottom, paint); //下边 canvas.drawrect(frame.left, frame.bottom - framestrokewidth, frame.right, frame.bottom, paint); } else { //边角在扫描区外 //左边 canvas.drawrect(frame.left - framestrokewidth, frame.top - framestrokewidth, frame.left, frame.bottom + framestrokewidth, paint); //上边 canvas.drawrect(frame.left - framestrokewidth, frame.top - framestrokewidth, frame.right + framestrokewidth, frame.top, paint); //右边 canvas.drawrect(frame.right, frame.top - framestrokewidth, frame.right + framestrokewidth, frame.bottom + framestrokewidth, paint); //下边 canvas.drawrect(frame.left - framestrokewidth, frame.bottom, frame.right + framestrokewidth, frame.bottom + framestrokewidth, paint); } } } //绘制边角 private void drawcorner(canvas canvas, rect frame) { if (cornersize > 0 && cornerstrokewidth > 0) { paint.setcolor(cornercolor); if (cornerposition == corner_inside) { //绘制在扫描区域内区 //左上 canvas.drawrect(frame.left, frame.top, frame.left + cornersize, frame.top + cornerstrokewidth, paint); canvas.drawrect(frame.left, frame.top, frame.left + cornerstrokewidth, frame.top + cornersize, paint); //右上 canvas.drawrect(frame.right - cornersize, frame.top, frame.right, frame.top + cornerstrokewidth, paint); canvas.drawrect(frame.right - cornerstrokewidth, frame.top, frame.right, frame.top + cornersize, paint); //左下 canvas.drawrect(frame.left, frame.bottom - cornersize, frame.left + cornerstrokewidth, frame.bottom, paint); canvas.drawrect(frame.left, frame.bottom - cornerstrokewidth, frame.left + cornersize, frame.bottom, paint); //右下 canvas.drawrect(frame.right - cornersize, frame.bottom - cornerstrokewidth, frame.right, frame.bottom, paint); canvas.drawrect(frame.right - cornerstrokewidth, frame.bottom - cornersize, frame.right, frame.bottom, paint); } else { //绘制在扫描区域外区 //左上 canvas.drawrect(frame.left - cornerstrokewidth, frame.top - cornerstrokewidth, frame.left - cornerstrokewidth + cornersize, frame.top, paint); canvas.drawrect(frame.left - cornerstrokewidth, frame.top - cornerstrokewidth, frame.left, frame.top - cornerstrokewidth + cornersize, paint); //右上 canvas.drawrect(frame.right + cornerstrokewidth - cornersize, frame.top - cornerstrokewidth, frame.right + cornerstrokewidth, frame.top, paint); canvas.drawrect(frame.right, frame.top - cornerstrokewidth, frame.right + cornerstrokewidth, frame.top - cornerstrokewidth + cornersize, paint); //左下 canvas.drawrect(frame.left - cornerstrokewidth, frame.bottom, frame.left - cornerstrokewidth + cornersize, frame.bottom + cornerstrokewidth, paint); canvas.drawrect(frame.left - cornerstrokewidth, frame.bottom + cornerstrokewidth - cornersize, frame.left, frame.bottom + cornerstrokewidth, paint); //右下 canvas.drawrect(frame.right + cornerstrokewidth - cornersize, frame.bottom, frame.right + cornerstrokewidth, frame.bottom + cornerstrokewidth, paint); canvas.drawrect(frame.right, frame.bottom + cornerstrokewidth - cornersize, frame.right + cornerstrokewidth, frame.bottom + cornerstrokewidth, paint); } } } //绘制文本 private void drawtextinfo(canvas canvas, rect frame) { if (!textutils.isempty(labeltext)) { paint.setcolor(labeltextcolor); paint.settextsize(labeltextsize); paint.settextalign(paint.align.center); paint.fontmetrics fm = paint.getfontmetrics(); float basey = frame.bottom + labeltextmargin - fm.ascent; canvas.drawtext(labeltext, frame.left + frame.width() / 2, basey, paint); } } //绘制扫描线 private void drawscanline(canvas canvas, rect frame) { if (lineheight > 0) { paint.setcolor(linecolor); radialgradient radialgradient = new radialgradient( (float) (frame.left + frame.width() / 2), (float) (scannerstart + lineheight / 2), 360f, linecolor, shadecolor(linecolor), shader.tilemode.mirror); paint.setshader(radialgradient); if (scannerstart <= scannerend) { //椭圆 rectf rectf = new rectf(frame.left + 2 * lineheight, scannerstart, frame.right - 2 * lineheight, scannerstart + lineheight); canvas.drawoval(rectf, paint); scannerstart += linemovedistance; } else { scannerstart = frame.top; } paint.setshader(null); } } private void drawresultpoint(canvas canvas, rect frame) { if (resultpointcolor != color.transparent) { 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); } } } } //处理颜色模糊 public int shadecolor(int color) { string hax = integer.tohexstring(color); string result = "20" + hax.substring(2); return integer.valueof(result, 16); } public void drawviewfinder() { invalidate(); } public void addpossibleresultpoint(resultpoint point) { possibleresultpoints.add(point); } private int dp2px(context context, float dpvalue) { float density = context.getapplicationcontext().getresources().getdisplaymetrics().density; return (int) (dpvalue * density + 0.5f); } private int sp2px(context context, float spvalue) { float scaledensity = context.getapplicationcontext().getresources().getdisplaymetrics().scaleddensity; return (int) (spvalue * scaledensity + 0.5f); } }
2、captureactivity:扫码的activity基类,代码如下;
/** * created by xuzhb on 2019/11/16 * desc:扫码的activity类 * 整个activity最重要的两个控件是一个surfaceview(摄像头)和一个viewfinderview(扫描区) * 对于继承captureactivity的activity子类来说, * 可以选择在自己的布局中定义和captureactivity的布局文件id相同的控件, * 这样即使它们在两个布局中表现不同也能执行相同的逻辑,包括其他控件 * 或者选择重写getsurfaceview()和getviewfinderview()返回对应的两个控件, * 扫码最终是在handledecode(result result, bitmap bitmap)处理扫描后的结果 */ public class captureactivity extends appcompatactivity implements surfaceholder.callback { private static final string tag = "captureactivity"; private static final int image_picker = 1999; private beepmanager mbeepmanager; private captureactivityhandler mhandler; private vector<barcodeformat> mdecodeformats; private string mcharacterset; private inactivitytimer minactivitytimer; private boolean hassurface = false; private boolean islighton = false; //是否打开闪光灯 private boolean isplaybeep = true; //是否开启扫描后的滴滴声 private boolean isvibrate = true; //是否震动 private string mphotopath; //选中的图片路径 private titlebar mtitlebar; private surfaceview msurfaceview; private viewfinderview mviewfinderview; private linearlayout mlightll; private imageview mlightiv; private textview mlighttv; @override protected void oncreate(@nullable bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(getlayoutid()); cameramanager.init(getapplicationcontext()); mbeepmanager = new beepmanager(this); hassurface = false; minactivitytimer = new inactivitytimer(this); handleview(savedinstancestate); initview(); initlistener(); } protected int getlayoutid() { return r.layout.activity_capture; } protected void handleview(@nullable bundle savedinstancestate) { } private void initview() { mtitlebar = findviewbyid(r.id.title_bar); msurfaceview = findviewbyid(r.id.surfaceview); mviewfinderview = findviewbyid(r.id.viewfinderview); mlightll = findviewbyid(r.id.light_ll); mlightiv = findviewbyid(r.id.light_iv); mlighttv = findviewbyid(r.id.light_tv); } protected void initlistener() { //因为继承captureactivity的activity子类的布局不一定包含id为title_bar和light_ll的控件, //没有的话如果子类通过super.initlistener()覆写时会因为找不到而报异常,所以这里加了一个判空; //如果子类的布局中包含id相同的控件,则不需要在子类中再重写相同的逻辑 if (mtitlebar != null) { statusbarutil.instance.darkmodeandpadding(this, mtitlebar, color.black, 0, false); mtitlebar.setonleftclicklistener(v -> { finish(); return null; }); mtitlebar.setonrightclicklistener(v -> { openalbum(); //打开相册选取图片扫描 return null; }); } if (mlightll != null) { mlightll.setonclicklistener(v -> switchlight()); //打开或关闭闪光灯 } } //打开相册 protected void openalbum() { intent intent = new intent(intent.action_pick, null); intent.setdataandtype(mediastore.images.media.external_content_uri, "image/*"); startactivityforresult(intent, image_picker); } //开启/关闭闪光灯 private void switchlight() { if (cameramanager.get() != null) { if (islighton) { mlighttv.settext("轻触点亮"); cameramanager.get().turnlightoffflashlight(); } else { mlighttv.settext("轻触关闭"); cameramanager.get().turnonflashlight(); } islighton = !islighton; mlightiv.setselected(islighton); } } @override protected void onresume() { super.onresume(); surfaceholder holder = getsurfaceview().getholder(); if (hassurface) { initcamera(holder); } else { holder.addcallback(this); holder.settype(surfaceholder.surface_type_push_buffers); } mdecodeformats = null; mcharacterset = null; } @override protected void onpause() { super.onpause(); if (mhandler != null) { mhandler.quitsynchronously(); mhandler = null; } cameramanager.get().closedriver(); } @override protected void ondestroy() { minactivitytimer.shutdown(); mbeepmanager.releasering(); super.ondestroy(); } @override public void surfacecreated(surfaceholder holder) { } @override public void surfacechanged(surfaceholder holder, int format, int width, int height) { if (!hassurface) { hassurface = true; initcamera(holder); } } @override public void surfacedestroyed(surfaceholder holder) { hassurface = false; } private void initcamera(surfaceholder holder) { try { cameramanager.get().opendriver(holder); } catch (exception e) { e.printstacktrace(); } if (mhandler == null) { mhandler = new captureactivityhandler(this, mdecodeformats, mcharacterset); } } //继承captureactivity的activity类,如果surfaceview的id和captureactivity布局中surfaceview的id不同 //需要重写这个方法,返回自己布局中的surfaceview public surfaceview getsurfaceview() { return msurfaceview; } //继承captureactivity的activity类,如果viewfinderview的id和captureactivity布局中viewfinderview的id不同 //需要重写这个方法,返回自己布局中的viewfinderview public viewfinderview getviewfinderview() { return mviewfinderview; } public handler gethandler() { return mhandler; } public void drawviewfinder() { getviewfinderview().drawviewfinder(); } //处理扫描后的结果 public void handledecode(result result, bitmap bitmap) { minactivitytimer.onactivity(); if (result != null) { string text = result.gettext(); log.i(tag, "识别的结果:" + text); if (!textutils.isempty(text)) { //识别成功 playbeepsoundandvibrate(); returnqrcoderesult(text); } else { showtoast("很抱歉,识别二维码失败!"); } } else { showtoast("未发现二维码!"); } } private void playbeepsoundandvibrate() { if (isplaybeep) { mbeepmanager.startring(); //播放扫码的滴滴声 } if (isvibrate) { vibrator vibrator = (vibrator) getsystemservice(context.vibrator_service); if (vibrator != null) { vibrator.vibrate(200); //震动200毫秒 } } } //返回扫描结果 private void returnqrcoderesult(string result) { intent intent = new intent(); intent.putextra(qrconstant.scan_qrcode_result, result); setresult(activity.result_ok, intent); finish(); } private void showtoast(charsequence text) { runonuithread(() -> { toastutil.instance.showtoast(text, true, false, getapplicationcontext()); }); } @override protected void onactivityresult(int requestcode, int resultcode, @nullable intent data) { super.onactivityresult(requestcode, resultcode, data); if (requestcode == image_picker && resultcode == activity.result_ok) { if (data != null) { uri uri = data.getdata(); if (uri != null) { cursor cursor = getcontentresolver().query(uri, null, null, null, null); if (cursor != null) { if (cursor.movetofirst()) { mphotopath = cursor.getstring(cursor.getcolumnindex(mediastore.images.media.data)); } cursor.close(); if (!textutils.isempty(mphotopath)) { //可以加个提示正在扫描的加载框,如showloadingdialog("正在扫描...") new thread(() -> { handledecode(qrcodeutil.decodeimage(mphotopath), null); //取消加载框,dismissloadingdialog() }).start(); } else { log.e(tag, "未找到图片"); } } } } } } }
看一下使用的例子
最后,附上整个项目的github地址,注:项目使用了视图绑定viewbinding,所以需要使用androidstudio 3.6.x版本。
到此这篇关于android集成zxing扫码框架功能的文章就介绍到这了,更多相关android zxing扫码内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!
上一篇: 产妇可以喝什么汤呢