快速集成扫码功能(定制扫描框)

扫码功能在我们的app中已经很常见了,提到二维码扫描,大家首先会想到著名的开源库ZXing。ZXing固然好,功能也很强大,但是我们在集成ZXing这个开源库的时候需要将其精简化,抽离出只与Android相关的部分。还好GitHub上一些开源作者已经帮我们进行了精简处理,在Android Studio中我们只需要添加相关的依赖即可,有没有很简单哈哈,在这里我们要感谢开源作者我们做出的贡献。在这里我选取了zxing-android-embedded这个开源库,下面我们一起学习下如何在我们的项目中快速集成扫码功能。

  1. 添加依赖
    compile('com.journeyapps:zxing-android-embedded:3.6.0') { transitive = false }
    compile 'com.google.zxing:core:3.3.0'
  1. 支持硬件加速
    根据GitHub上面的文档,“Hardware accelation is required since TextureView is used.”意思就是说自从使用TextureView之后,硬件加速是有需要的。在manifest文件的application节点下添加:android:hardwareAccelerated="true"。

这样子我们就可以在代码中使用扫码功能了,关于扫码的API我在这里就不介绍了,大家可以点击GitHub文档进行查看,当然我们也可以将这个开源库的代码下载到本地,上面有一些常用sample。代码运行后我们会发现,扫码界面是不是有些“简陋”了点,这样子UI小姐姐肯定不会放过我们的,下面我们一起学习下怎么定制扫描框。

相信你在查看sample的时候会发现在布局文件中会出现DecoratedBarcodeView:

    <com.journeyapps.barcodescanner.DecoratedBarcodeView
        android:id="@+id/zxing_barcode_scanner"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:zxing_scanner_layout="@layout/custom_barcode_scanner">
    </com.journeyapps.barcodescanner.DecoratedBarcodeView>

what???这是个什么东西,充满好奇心的我们肯定要点进去看一下:

/**
 * Encapsulates BarcodeView, ViewfinderView and status text.
 *
 * To customize the UI, use BarcodeView and ViewfinderView directly.
 */
public class DecoratedBarcodeView extends FrameLayout {
    private BarcodeView barcodeView;
    private ViewfinderView viewFinder;
    private TextView statusView;

看下上面的注释我们就明白了,原来DecoratedBarcodeView相当于将BarcodeView、ViewfinderView进行包装了一下,方便我们进行操作,作者建议我们:如果想要定制UI显示效果,直接使用BarcodeView、ViewfinderView就好。在这里我先说下,ViewfinderView就是我们定制扫码界面所使用到的。下面我们一起来尝试下:

  1. 新建BarcodeScanActivity作为扫码Activity,根据作者给出的sample,在该activity的布局文件中将BarcodeView和ViewfinderView添加进来,然后在activity中获得控件即可,BarcodeScanActivity中的关键代码如下:
        mBarcodeView = findViewById(R.id.mBarcodeView);          //取得控件
        mFinderView = findViewById(R.id.mFinderView);

        mFinderView.setCameraPreview(mBarcodeView);              //将BarcodeView和ViewfinderView关联起来
        mBarcodeView.decodeContinuous(callback);                 //设置扫码回调

然后我们就可以运行了(注意添加照相机权限!!!),运行完毕你会发现和作者给出的sample效果完全一样,下面我们就要自己定制扫码界面了。

  1. 定制扫码界面
    定制扫码界面其实就是一个简单的自定义效果,我们自己“绘制”出来自己想要的界面。
    新建CustomFinderView继承自ViewfinderView。以主流的扫码框为例,我们自定义属性的时候需要考虑到:扫码界面背景颜色、矩形框颜色、矩形框外侧四个“L”颜色、“L”高度等等。然后就需要我们重写onDraw方法来进行绘制了。下面贴出CustomFinderView代码,相信大家都能理解。
public class CustomFinderView extends ViewfinderView{

    private static final int DEFAULT_MASK_COLOR = 0X80000000;
    private static final int DEFAULT_RECT_COLOR = 0XFFFFFFFF;
    private static final int DEFAULT_CORNER_COLOR = 0XFF339933;
    private static final int DEFAULT_CORNER_WIDTH = 4;
    private static final int DEFAULT_CORNER_HEIGHT = 16;

    private int mMaskColor;

    private int mRectColor;

    private int mCornerColor;

    private int mCornerWidth;

    private int mCornerHeight;

    private int mScanLineResId;
    private Paint mRectPaint;
    private Paint cornerPaint;
    private Bitmap mLineBitmap;

    private int mScanTop = -1;

    public CustomFinderView(Context context, AttributeSet attrs) {
        super(context, attrs);

        initializeAttributes(attrs);

        initPaint();
    }

    private void initializeAttributes(AttributeSet attrs){
        TypedArray attributes = getContext().obtainStyledAttributes(attrs,R.styleable.CustomFinderView);

        this.mMaskColor = attributes.getColor(R.styleable.CustomFinderView_color_scan_mask,
                DEFAULT_MASK_COLOR);
        this.mRectColor = attributes.getColor(R.styleable.CustomFinderView_color_scan_rect,
                DEFAULT_RECT_COLOR);
        this.mCornerColor = attributes.getColor(R.styleable.CustomFinderView_color_scan_corner,
                DEFAULT_CORNER_COLOR);
        this.mCornerWidth = (int) attributes.getDimension(
                        R.styleable.CustomFinderView_width_scan_corner, dp2px(DEFAULT_CORNER_WIDTH));
        this.mCornerHeight = (int) attributes.getDimension(
                R.styleable.CustomFinderView_height_scan_corner, dp2px(DEFAULT_CORNER_HEIGHT));
        this.mScanLineResId = attributes.getResourceId(R.styleable.CustomFinderView_line_center_drawable,-1);

        attributes.recycle();
    }

    private void initPaint(){
        mRectPaint = new Paint();
        mRectPaint.setAntiAlias(true);
        mRectPaint.setColor(mRectColor);
        mRectPaint.setStrokeWidth(dp2px(1));
        mRectPaint.setStyle(Paint.Style.STROKE);

        cornerPaint = new Paint();
        cornerPaint.setAntiAlias(true);
        cornerPaint.setColor(mCornerColor);
        cornerPaint.setStrokeWidth(mCornerWidth);

        if (mScanLineResId != -1) {
            mLineBitmap = BitmapFactory.decodeResource(getResources(), mScanLineResId);
        }
    }

    @Override
    public void onDraw(Canvas canvas) {
        refreshSizes();

        if (framingRect == null || previewFramingRect == null) {
            return;
        }

        final Rect frame = framingRect;

        final int width = canvas.getWidth();
        final int height = canvas.getHeight();
        paint.setAntiAlias(true);

        // Draw the exterior (i.e. outside the framing rect) darkened
        paint.setColor(mMaskColor);
        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);

        //Draw the Rect side
        RectF sideRect = new RectF(frame.left-mRectPaint.getStrokeWidth()/2,frame.top-mRectPaint.getStrokeWidth()/2,
                frame.right+mRectPaint.getStrokeWidth()/2,frame.bottom+mRectPaint.getStrokeWidth()/2);
        canvas.drawRect(sideRect,mRectPaint);

        //Draw the Rect corner
        float mSideLeft = frame.left - mRectPaint.getStrokeWidth();
        float mSideRight = frame.right + mRectPaint.getStrokeWidth();
        float mSlideTop = frame.top - mRectPaint.getStrokeWidth();
        float mSlideBottom = frame.bottom + mRectPaint.getStrokeWidth();

        canvas.drawLine(mSideLeft-mCornerWidth,mSlideTop-mCornerWidth/2,
                mSideLeft+mCornerHeight,mSlideTop-mCornerWidth/2,cornerPaint);
        canvas.drawLine(mSideRight+mCornerWidth,mSlideTop-mCornerWidth/2,
                mSideRight-mCornerHeight,mSlideTop-mCornerWidth/2,cornerPaint);

        canvas.drawLine(mSideLeft-mCornerWidth/2,mSlideTop,
                mSideLeft-mCornerWidth/2,mSlideTop+mCornerHeight,cornerPaint);
        canvas.drawLine(mSideRight+mCornerWidth/2,mSlideTop,
                mSideRight+mCornerWidth/2,mSlideTop+mCornerHeight,cornerPaint);

        canvas.drawLine(mSideLeft-mCornerWidth/2,mSlideBottom,
                mSideLeft-mCornerWidth/2,mSlideBottom-mCornerHeight,cornerPaint);
        canvas.drawLine(mSideRight+mCornerWidth/2,mSlideBottom,
                mSideRight+mCornerWidth/2,mSlideBottom-mCornerHeight,cornerPaint);

        canvas.drawLine(mSideLeft-mCornerWidth,mSlideBottom+mCornerWidth/2,
                mSideLeft+mCornerHeight,mSlideBottom+mCornerWidth/2,cornerPaint);
        canvas.drawLine(mSideRight+mCornerWidth,mSlideBottom+mCornerWidth/2,
                mSideRight-mCornerHeight,mSlideBottom+mCornerWidth/2,cornerPaint);

        //Draw the scan line
        if (mLineBitmap == null){
                mLineBitmap = BitmapFactory.decodeResource(getResources(),mScanLineResId);
        }

        if (mLineBitmap != null){

            if (mScanTop == -1){
                mScanTop = frame.top;
            }

            if (mScanTop >= frame.bottom - dp2px(2)){
                mScanTop = frame.top;
            }

            RectF destRect = new RectF(frame.left+dp2px(2),mScanTop,frame.right-dp2px(2),
                    mScanTop + dp2px(2));
            canvas.drawBitmap(mLineBitmap,null,destRect,cornerPaint);

            mScanTop = mScanTop +dp2px(4);
            postInvalidateDelayed(60,frame.left+dp2px(2),mScanTop,frame.right-dp2px(2),
                    mScanTop + dp2px(2));

        }

    }

    protected int dp2px(int dpVal) {
        return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,
                dpVal, getResources().getDisplayMetrics());
    }
}

最后的运行效果:


扫码界面
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 159,458评论 4 363
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,454评论 1 294
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 109,171评论 0 243
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 44,062评论 0 207
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,440评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,661评论 1 219
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,906评论 2 313
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,609评论 0 200
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,379评论 1 246
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,600评论 2 246
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,085评论 1 261
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,409评论 2 254
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,072评论 3 237
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,088评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,860评论 0 195
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,704评论 2 276
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,608评论 2 270

推荐阅读更多精彩内容

  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 170,569评论 25 707
  • 这招玩的真好,麻蛋
    车尾靠窗阅读 165评论 0 0
  • 隐藏自己的疲倦 表达自己的狼狈放纵自己的狂野 找寻自己的明天音乐在此戛然而止 正是一份合适的安慰 古今如梦 ...
    NoneLand阅读 214评论 0 0
  • 21年来,我从不曾忘记,却也不敢想起。每一次的从梦中哭醒,都是因为对奶奶的思念。都说幺儿最亲,而我在奶奶...
    陌上桑1123阅读 136评论 0 0
  • 书法课 书法中凝聚着中华民族的哲学思想、美学追求、人文精神、聪明才智、思想感情,是一个反映生命的艺术,已成为整个中...
    清水常天阅读 184评论 0 1