1. 程式人生 > 其它 >安卓使用zxing生成二維碼

安卓使用zxing生成二維碼

技術標籤:安卓安卓

前言:時至今日,二維碼的用途非常廣泛,前段時間,有人找我要一個輸入字串生成二維碼的apk,想想這個簡單,就寫了一個!

先導包

implementation 'com.google.zxing:core:3.2.1'
implementation 'cn.bingoogolapple:bga-qrcodecore:[email protected]'
implementation 'cn.bingoogolapple:bga-zxing:[email protected]'

implementation 'com.github.bumptech.glide:glide:4.9.0'
annotationProcessor 'com.github.bumptech.glide:compiler:4.9.0'

這裡我使用了zxing以及glide,前者是生成二維碼的庫,後者是圖片載入框架,網上都有示例我就不介紹了,今天主要是介紹二維碼生成器,不廢話了直接上程式碼,先佈局,後代碼:

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

    <EditText
            android:id="@+id/Numbers"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_margin="@dimen/x10"
            android:hint="請輸入所要轉化成二維碼的內容"
            android:padding="@dimen/x10"
            android:text="網路異常" />


    <EditText
            android:id="@+id/ColorCode"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:hint="請輸入二維碼顏色值(範圍0-10.預設0黑色)"
            android:padding="@dimen/x10"
            android:text="0" />


    <Button
            android:id="@+id/QrCode"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="生成二維碼" />

   

    <ImageView
            android:id="@+id/QrCodeImage"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_margin="@dimen/x10" />


</LinearLayout>

這裡主要就四個控制元件,一個是內容,一個是顏色值,這個值是自己可以控制的,等會你們就知道了,剩下一個按鈕一個imageview是顯示二維碼的

package com.airiche.qrcodetest

import android.graphics.Color
import android.os.Bundle
import android.text.TextUtils
import android.util.Log
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import com.bumptech.glide.Glide
import kotlinx.android.synthetic.main.activity_main.*

class MainActivity : AppCompatActivity() {
    
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        QrCode.setOnClickListener {
            //生成二維碼
            var context = Numbers.text.trim().toString()
            var mColor = Color.BLACK
            when (ColorCode.text.toString()) {
                "0" -> {
                    mColor = Color.BLACK
                }
                "1" -> {
                    mColor = Color.DKGRAY
                }
                "2" -> {
                    mColor = Color.GRAY
                }
                "3" -> {
                    mColor = Color.LTGRAY
                }
                "4" -> {
                    mColor = Color.WHITE
                }
                "5" -> {
                    mColor = Color.RED
                }
                "6" -> {
                    mColor = Color.GREEN
                }
                "7" -> {
                    mColor = Color.BLUE
                }
                "8" -> {
                    mColor = Color.YELLOW
                }
                "9" -> {
                    mColor = Color.CYAN
                }
                "10" -> {
                    mColor = Color.MAGENTA
                }
            }
            var bitmap = ZXingUtils.createQRImage(context, 800, 800, mColor)
            Glide.with(this).load(bitmap).into(QrCodeImage)
        }
    }
}

這裡的顏色值是我們自己控制的,最終的生成就在ZXingUtils

package com.airiche.qrcodetest;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.PointF;
import android.view.Gravity;
import android.view.View;
import android.view.WindowManager;
import android.widget.TextView;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;

import java.util.Hashtable;

/**
 *   生成條形碼和二維碼的工具
 */
public class ZXingUtils {
    /**
     * 生成二維碼 要轉換的地址或字串,可以是中文
     *
     * @param url
     * @param width
     * @param height
     * @return
     */
    public static Bitmap createQRImage(String url, final int width, final int height,int color) {
        try {
            // 判斷URL合法性
            if (url == null || "".equals(url) || url.length() < 1) {
                return null;
            }
            Hashtable<EncodeHintType, String> hints = new Hashtable<EncodeHintType, String>();
            hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
            // 影象資料轉換,使用了矩陣轉換
            BitMatrix bitMatrix = new QRCodeWriter().encode(url,
                    BarcodeFormat.QR_CODE, width, height, hints);
            int[] pixels = new int[width * height];
            // 下面這裡按照二維碼的演算法,逐個生成二維碼的圖片,
            // 兩個for迴圈是圖片橫列掃描的結果
            for (int y = 0; y < height; y++) {
                for (int x = 0; x < width; x++) {
                    if (bitMatrix.get(x, y)) {
                        pixels[y * width + x] = color;
                    } else {
                        pixels[y * width + x] = 0xffffffff;
                    }
                }
            }
            // 生成二維碼圖片的格式,使用ARGB_8888
            Bitmap bitmap = Bitmap.createBitmap(width, height,
                    Bitmap.Config.ARGB_8888);
            bitmap.setPixels(pixels, 0, width, 0, 0, width, height);
            return bitmap;
        } catch (WriterException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 生成條形碼
     *
     * @param context
     * @param contents
     *            需要生成的內容
     * @param desiredWidth
     *            生成條形碼的寬頻
     * @param desiredHeight
     *            生成條形碼的高度
     * @param displayCode
     *            是否在條形碼下方顯示內容
     * @return
     */
    public static Bitmap creatBarcode(Context context, String contents,
                                      int desiredWidth, int desiredHeight, boolean displayCode) {
        Bitmap ruseltBitmap = null;
        /**
         * 圖片兩端所保留的空白的寬度
         */
        int marginW = 20;
        /**
         * 條形碼的編碼型別
         */
        BarcodeFormat barcodeFormat = BarcodeFormat.CODE_128;

        if (displayCode) {
            Bitmap barcodeBitmap = encodeAsBitmap(contents, barcodeFormat,
                    desiredWidth, desiredHeight);
            Bitmap codeBitmap = creatCodeBitmap(contents, desiredWidth + 2
                    * marginW, desiredHeight, context);
            ruseltBitmap = mixtureBitmap(barcodeBitmap, codeBitmap, new PointF(
                    0, desiredHeight));
        } else {
            ruseltBitmap = encodeAsBitmap(contents, barcodeFormat,
                    desiredWidth, desiredHeight);
        }

        return ruseltBitmap;
    }

    /**
     * 生成條形碼的Bitmap
     *
     * @param contents
     *            需要生成的內容
     * @param format
     *            編碼格式
     * @param desiredWidth
     * @param desiredHeight
     * @return
     * @throws WriterException
     */
    protected static Bitmap encodeAsBitmap(String contents,
                                           BarcodeFormat format, int desiredWidth, int desiredHeight) {
        final int WHITE = 0xFFFFFFFF;
        final int BLACK = 0xFF000000;

        MultiFormatWriter writer = new MultiFormatWriter();
        BitMatrix result = null;
        try {
            result = writer.encode(contents, format, desiredWidth,
                    desiredHeight, null);
        } catch (WriterException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        int width = result.getWidth();
        int height = result.getHeight();
        int[] pixels = new int[width * height];
        // All are 0, or black, by default
        for (int y = 0; y < height; y++) {
            int offset = y * width;
            for (int x = 0; x < width; x++) {
                pixels[offset + x] = result.get(x, y) ? BLACK : WHITE;
            }
        }

        Bitmap bitmap = Bitmap.createBitmap(width, height,
                Bitmap.Config.ARGB_8888);
        bitmap.setPixels(pixels, 0, width, 0, 0, width, height);
        return bitmap;
    }

    /**
     * 生成顯示編碼的Bitmap
     *
     * @param contents
     * @param width
     * @param height
     * @param context
     * @return
     */
    protected static Bitmap creatCodeBitmap(String contents, int width,
                                            int height, Context context) {
        TextView tv = new TextView(context);
        WindowManager.LayoutParams layoutParams = new WindowManager.LayoutParams(
                WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.WRAP_CONTENT);
        tv.setLayoutParams(layoutParams);
        tv.setText(contents);
        tv.setHeight(height);
        tv.setGravity(Gravity.CENTER_HORIZONTAL);
        tv.setWidth(width);
        tv.setDrawingCacheEnabled(true);
        tv.setTextColor(Color.BLACK);
        tv.measure(View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED),
                View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
        tv.layout(0, 0, tv.getMeasuredWidth(), tv.getMeasuredHeight());

        tv.buildDrawingCache();
        Bitmap bitmapCode = tv.getDrawingCache();
        return bitmapCode;
    }

    /**
     * 將兩個Bitmap合併成一個
     *
     * @param first
     * @param second
     * @param fromPoint
     *            第二個Bitmap開始繪製的起始位置(相對於第一個Bitmap)
     * @return
     */
    protected static Bitmap mixtureBitmap(Bitmap first, Bitmap second,
                                          PointF fromPoint) {
        if (first == null || second == null || fromPoint == null) {
            return null;
        }
        int marginW = 20;
        Bitmap newBitmap = Bitmap.createBitmap(
                first.getWidth() + second.getWidth() + marginW,
                first.getHeight() + second.getHeight(), Bitmap.Config.ARGB_4444);
        Canvas cv = new Canvas(newBitmap);
        cv.drawBitmap(first, marginW, 0, null);
        cv.drawBitmap(second, fromPoint.x, fromPoint.y, null);
        cv.save();
        cv.restore();

        return newBitmap;
    }

}

這就是最簡單二維碼生成器,其實Zxing還能生成條形碼之類的,也很簡單!這裡只介紹二維碼,你們可以自己去玩!