初学安卓之二维码的简单实现

本文详细介绍了如何在安卓应用中实现二维码的生成和扫描功能。通过集成ZXing开源库,分别展示了如何创建生成二维码的Activity,修改二维码颜色,添加Logo,以及实现扫描二维码并返回内容的功能。此外,还提供了相应的代码片段和参考资料。
摘要由CSDN通过智能技术生成

前言

随着互联网的发展,在网上的二维码种类和作用越来越多,因此我想着自己也实现生成二维码以及扫码。经过上网查资料发现,大多实现二维码功能的,主要都是靠集成了ZXing开源项目的功能,目前还有人在维护,足够我们学习使用。

生成二维码

准备工作

  • 在ZXing开源库中我们可以看到它已经升级到了3.4.0,于是导入3.4.0的依赖
    在这里插入图片描述
  • build.gradle中添加依赖com.google.zxing:core:3.4.0
apply plugin: 'com.android.application'

android {
   
    compileSdkVersion 29
    buildToolsVersion "29.0.3"
    defaultConfig {
   
        applicationId "com.example.qrcodetest"
        minSdkVersion 19
        targetSdkVersion 29
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
   
        release {
   
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
   
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'androidx.appcompat:appcompat:1.1.0'
    implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'androidx.test.ext:junit:1.1.1'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'

    implementation 'com.google.zxing:core:3.4.0'

}
  • activity_main.xml文件中添加两个按钮,一个是生成二维码,一个是扫描二维码,并在MainActivity中添加监听按钮点击,实现以下界面
    主界面

生成简单二维码

  1. 创建一个名为GenerateQRcode的Activity,Android Studio自动生成其布局文件,布局文件改名为generate_qrcode.xml:放置一个EditText输入二维码内容、一个Button监听操作以及一个ImageView提供二维码的显示,对应的string在string.xml中添加
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">


    <EditText
        android:id="@+id/editText"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentEnd="true"
        android:text="@string/firstTest"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <Button
        android:id="@+id/btn"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/generate_btn"
        app:layout_constraintTop_toBottomOf="@+id/editText"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"/>

    <ImageView
        android:id="@+id/imageView"
        android:layout_width="256dp"
        android:layout_height="256dp"
        android:layout_centerInParent="true"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />


</androidx.constraintlayout.widget.ConstraintLayout>
    <string name="firstTest">https://www.baidu.com</string>
    <string name="generate_btn">生成二维码</string>
  1. AndroidManifest.xml中注册(Android Studio会自动生成)
	<application
        ...
        <activity android:name=".GenerateQRcode"></activity>
        ...
    </application>
  1. 要实现二维码的生成,主要是靠zxing提供的接口和方法,在GenerateQRcode文件中新建一个generateSimpleBitmap方法用于生成二维码,参数为二维码内容、宽和高,并将参数传入到QRCodeWriterencode方法生成BitMatrix对象,创建一个大小为二维码宽*高的数组,根据BitMatrix对象,往其中放置黑白色块,最后使用createBitmap返回一个Bitmap对象
private Bitmap generateSimpleBitmap(String content, int width, int height) {
   
        // 字符串内容判空
        if (TextUtils.isEmpty(content)) {
   
            Toast.makeText(getApplicationContext(),"输入为空!",Toast.LENGTH_LONG).show();
            return null;
        }

        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 y = 0; y < height; y++) {
   
                for (int x = 0; x < width; x++) {
   
                    if (encode.get(x, y)) {
   
                        pixels[y * width + x] = 0x00000000;
                    } else {
   
                        pixels[y * width + x] = 0xFFFFFFFF;
                    }
                }
            }
            return Bitmap.createBitmap(pixels, 0, width, width, height, Bitmap.Config.RGB_565);
        } catch (WriterException e) {
   
            e.printStackTrace();
        }
        return null;
    }
  1. GenerateQRcode文件中的onCreate引用,将结果注入布局的ImageView组件中
protected void onCreate(Bundle savedInstanceState) {
   
        super.onCreate(savedInstanceState);
        setContentView(R.layout.generate_qrcode);

        btn = (Button)findViewById(R.id.btn);
        editText = (EditText)findViewById(R.id.editText);
        imageView = (ImageView)findViewById(R.id.imageView);
        btn.setOnClickListener(new View.OnClickListener() {
   
            @Override
            public void onClick(View view) {
   
                String content = editText.getText().toString();
                Bitmap qrBitmap = generateSimpleBitmap(content,256, 256);
                imageView.setImageBitmap(qrBitmap);
            }
        });
    }
  1. 实现结果
    SimpleBitmap

修改二维码颜色

  1. 在以上基础上,在GenerateQRcode文件中新建一个generateQRCodeBitmap方法,相比generateSimpleBitmap,参数多了两个颜色,一个为原二维码黑点的颜色,另一个为原来白色的背景颜色
public Bitmap generateQRCodeBitmap(String content, int width, int height,
                                       int color_point, int color_back) {
   
        //字符串内容判空
        if (TextUtils.isEmpty(content)) {
   
            Toast.makeText(getApplicationContext(),"输入为空!",Toast.LENGTH_LONG).show();
            return null;
        }
        Map<EncodeHintType, String> hints = new HashMap<>();
        //格式utf-8
        hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
        //空白边距设置
        hints.put(EncodeHintType.MARGIN, "1")
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值