必威体育Betway必威体育官网
当前位置:首页 > IT技术

安卓Zxing的简单使用-(生成二维码与扫一扫)

时间:2019-08-23 00:42:18来源:IT技术作者:seo实验室小编阅读:57次「手机版」
 

zxing

前言:zxing -github链接:https://github.com/zxing/zxing

1、效果图:

这里写图片描述

zxing自带扫码界面(横屏)

这里写图片描述

自定义扫码界面

这里写图片描述

2、

build.gradle中加入

implementation 'com.journeyAPPs:zxing-Android-embedded:3.6.0'

3、MainActivity:

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private ImageView imageView;
    private TextView textView;
    private EditText editText;

    @Override
    protected void onCreate(Bundle savedinstanceState) {
        super.onCreate(savedInstanceState);
        setcontentView(R.layout.activity_main);
        imageView = this.findViewById(R.id.imageView_zxing);
        textView = this.findViewById(R.id.textview_zxing);
        editText = this.findViewById(R.id.edittext_zxing);

        findViewById(R.id.button_zxing).setOnClickListener(this);
        findViewById(R.id.button_start).setOnClickListener(this);
        findViewById(R.id.button_native).setOnClickListener(this);
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.button_zxing:
                String count = editText.getText().toString().trim();
                if (TextUtils.isempty(count)) {
                    toast.maketext(MainActivity.this, "请输入内容", Toast.LENGTH_LONG).show();
                    return;
                }
                //生成二维码显示在imageView上
                imageView.setImageBitmap(generateBitmap(count, 600, 600));
                break;
            case R.id.button_start:
                new intentIntegrator(this)
                        .setDesiredBarcodeFormats(IntentIntegrator.ALL_CODE_types)// 扫码的类型,可选:一维码,二维码,一/二维码
                        //.setPrompt("请对准二维码")// 设置提示语
                        .setCameraId(0)// 选择摄像头,可使用前置或者后置
                        .setBeepEnabled(true)// 是否开启声音,扫完码之后会"哔"的一声
                        .initiateScan();// 初始化扫码
                break;
            case R.id.button_native:
                new IntentIntegrator(this)
                        .setDesiredBarcodeFormats(IntentIntegrator.ALL_CODE_TYPES)// 扫码的类型,可选:一维码,二维码,一/二维码
                        //.setPrompt("请对准二维码")// 设置提示语
                        .setCameraId(0)// 选择摄像头,可使用前置或者后置
                        .setBeepEnabled(true)// 是否开启声音,扫完码之后会"哔"的一声
                        .setCaptureActivity(QrCodeActivity.class)//自定义扫码界面
                        .initiateScan();// 初始化扫码
                break;
        }
    }

    /**
     * 生成固定大小的二维码(不需网络权限)
     *
     * @param content 需要生成的内容
     * @param width   二维码宽度
     * @param height  二维码高度
     * @return
     */
    private Bitmap generateBitmap(String content, int width, int height) {
        QRCodeWriter qrCodeWriter = new QRCodeWriter();
        Map<EncodeHintType, String> hints = new HashMap<>();
        hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
        try {
            BitMatrix encode = qrCodeWriter.encode(content, BarcodeFormat.QR_CODE, width, height, hints);
            int[] pixels = new int[width * height];
            for (int i = 0; i < height; i++) {
                for (int j = 0; j < width; j++) {
                    if (encode.get(j, i)) {
                        pixels[i * width + j] = 0x00000000;
                    } else {
                        pixels[i * width + j] = 0xffffffff;
                    }
                }
            }
            return Bitmap.createBitmap(pixels, 0, width, width, height, Bitmap.Config.RGB_565);
        } catch (WriterException e) {
            e.printstacktrace();
        }
        return null;
    }

    @Override
    protected void onActivityResult(int requestcode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        //扫码结果
        IntentResult intentResult = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);
        if (intentResult != null) {
            if (intentResult.getContents() == null) {
                //扫码失败
            } else {
                String result = intentResult.getContents();//返回值
                textView.setText("扫码结果:" + result);
            }
        }
    }
}

CustomZxingView自定义扫码View

public class CustomZxingView extends ViewfinderView {

    public int laserLinePosition = 0;
    public float[] position = new float[]{0f, 0.5f, 1f};
    public int[] colors = new int[]{0xff0699e6, 0xff0699e6, 0xff0699e6};
    public LinearGradient linearGradient;

    public CustomZxingView(context context, AttributeSet attrs) {
        super(context, attrs);
    }

    /**
     * 重写draw方法绘制自己的扫描框
     *
     * @param canvas
     */
    @Override
    public void onDraw(Canvas canvas) {
        refreshSizes();
        if (framingRect == null || previewFramingRect == null) {
            return;
        }

        Rect frame = framingRect;
        Rect previewFrame = previewFramingRect;

        int width = canvas.getWidth();
        int height = canvas.getHeight();
        //绘制4个角

        paint.setColor(Color.parseColor("#139D57"));//定义画笔的颜色
        canvas.drawRect(frame.left, frame.top, frame.left + 100, frame.top + 10, paint);
        canvas.drawRect(frame.left, frame.top, frame.left + 10, frame.top + 100, paint);

        canvas.drawRect(frame.right - 100, frame.top, frame.right, frame.top + 10, paint);
        canvas.drawRect(frame.right - 10, frame.top, frame.right, frame.top + 100, paint);

        canvas.drawRect(frame.left, frame.bottom - 10, frame.left + 100, frame.bottom, paint);
        canvas.drawRect(frame.left, frame.bottom - 100, frame.left + 10, frame.bottom, paint);

        canvas.drawRect(frame.right - 100, frame.bottom - 10, frame.right, frame.bottom, paint);
        canvas.drawRect(frame.right - 10, frame.bottom - 100, frame.right, frame.bottom, paint);
        // Draw the exterior (i.e. outside the framing rect) darkened
        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(CURRENT_POINT_OPACITY);
            canvas.drawbitmap(resultBitmap, null, frame, paint);
        } else {
            int middle = frame.height() / 2 + frame.top;
            laserLinePosition = laserLinePosition + 5;
            if (laserLinePosition > frame.height()) {
                laserLinePosition = 0;
            }
            linearGradient = new LinearGradient(frame.left + 1, frame.top + laserLinePosition, frame.right - 1, frame.top + 10 + laserLinePosition, colors, position, shader.TileMode.CLAMP);
            // Draw a red "laser scanner" line through the middle to show decoding is active
            paint.setShader(linearGradient);
            //绘制扫描线
            canvas.drawRect(frame.left + 1, frame.top + laserLinePosition, frame.right - 1, frame.top + 10 + laserLinePosition, paint);
            paint.setShader(null);
            float scaleX = frame.width() / (float) previewFrame.width();
            float scaleY = frame.height() / (float) previewFrame.height();

            List<ResultPoint> currentPossible = possibleResultPoints;
            List<ResultPoint> currentLast = lastPossibleResultPoints;
            int frameLeft = frame.left;
            int frameTop = frame.top;
            if (currentPossible.isEmpty()) {
                lastPossibleResultPoints = null;
            } else {
                possibleResultPoints = new ArrayList<>(5);
                lastPossibleResultPoints = currentPossible;
                paint.setAlpha(CURRENT_POINT_OPACITY);
                paint.setColor(resultPointColor);
                for (ResultPoint point : currentPossible) {
                    canvas.drawCircle(frameLeft + (int) (point.getX() * scaleX),
                            frameTop + (int) (point.getY() * scaleY),
                            POINT_SIZE, paint);
                }
            }
            if (currentLast != null) {
                paint.setAlpha(CURRENT_POINT_OPACITY / 2);
                paint.setColor(resultPointColor);
                float radius = POINT_SIZE / 2.0f;
                for (ResultPoint point : currentLast) {
                    canvas.drawCircle(frameLeft + (int) (point.getX() * scaleX),
                            frameTop + (int) (point.getY() * scaleY),
                            radius, paint);
                }
            }
            postinvalidateDelayed(16,
                    frame.left,
                    frame.top,
                    frame.right,
                    frame.bottom);
        }
    }
}

QrCodeActivity:

public class QrCodeActivity extends AppCompatActivity implements  DecoratedBarcodeView.TorchListener {

    private DecoratedBarcodeView decoratedBarcodeView;
    private CaptureManager captureManager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_qr_code);

        decoratedBarcodeView=this.findViewById(R.id.decoratedBarcodeView);
        //重要代码,初始化捕获
        captureManager = new CaptureManager(this, decoratedBarcodeView);
        captureManager.initializeFromIntent(getIntent(), savedInstanceState);
        captureManager.decode();
        decoratedBarcodeView.setTorchListener(this);
    }

    @Override
    public void onTorchOn() {

    }

    @Override
    public void onTorchOff() {

    }

    @Override
    protected void onpause() {
        super.onPause();
        captureManager.onPause();
    }

    @Override
    protected void onResume() {
        super.onResume();
        captureManager.onResume();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        captureManager.onDestroy();
    }

    @Override
    public void onSaveInstanceState(Bundle outState, persistableBundle outPersistentState) {
        super.onSaveInstanceState(outState, outPersistentState);
        captureManager.onSaveInstanceState(outState);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        return decoratedBarcodeView.onKeyDown(keyCode, event) || super.onKeyDown(keyCode, event);
    }
}

4、布局文件

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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:orientation="vertical"
    android:padding="5dp"
    tools:context=".MainActivity">

    <EditText
        android:id="@+id/edittext_zxing"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="输入需要生成二维码的内容" />

    <Button
        android:id="@+id/button_zxing"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="生成二维码" />

    <ImageView
        android:id="@+id/imageView_zxing"
        android:layout_width="match_parent"
        android:layout_height="250dp" />

    <Button
        android:id="@+id/button_start"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="开启扫一扫(zxing自带扫码界面)" />

    <Button
        android:layout_margintop="10dp"
        android:id="@+id/button_native"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="开启扫一扫(自定义扫码界面)" />


    <TextView
        android:id="@+id/textview_zxing"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="扫码的结果" />

</LinearLayout>

activity_qr_code.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <com.journeyapps.barcodescanner.DecoratedBarcodeView
        android:id="@+id/decoratedBarcodeView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:zxing_framing_rect_height="250dp"
        app:zxing_framing_rect_width="250dp"
        app:zxing_preview_scaling_strategy="fitXY"
        app:zxing_scanner_layout="@layout/layout_zxing"
        app:zxing_use_texture_view="true" />

</LinearLayout>

layout_zxing.xml

<?xml version="1.0" encoding="utf-8"?>
<merge xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <com.journeyapps.barcodescanner.BarcodeView
        android:id="@+id/zxing_barcode_surface"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:zxing_framing_rect_height="300dp"
        app:zxing_framing_rect_width="300dp" />

    <com.helloworld.zxingdemo.CustomZxingView
        android:id="@+id/zxing_viewfinder_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:zxing_possible_result_points="#139D57"
        app:zxing_result_view="@color/zxing_custom_result_view"
        app:zxing_viewfinder_laser="#fff"
        app:zxing_viewfinder_mask="#60000000" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom|center_horizontal"
        android:layout_marginBottom="20dp"
        android:text="请对准二维码开始扫描"
        android:textColor="#fff" />

</merge>

相关阅读

超简单集成Android Zxing实现扫一扫二维码

2017-10-20更新最新版本的请看 超简单一句话依赖使用二维码扫描,优化了扫描速度,修复了一些bug,增加了闪光灯,解析二维码图片,生成二维

Zxing jar的下载地址

http://repo1.maven.org/maven2/com/google/zxing/core/

二维码框架Zxing的使用及自定义

项目需要一个二维码扫描功能 关于二维码的扫描,我之前就听说过ZXing了(虽然从来没用过) 所以既然这次要用它了,自然是得搜索一番资料

分享到:

栏目导航

推荐阅读

热门阅读