Android 中可以使用 Zxing 库生成二维码,具体步骤如下:

  1. 在 build.gradle 文件中添加依赖:
dependencies {
    implementation 'com.google.zxing:core:3.4.0'
    implementation 'com.journeyapps:zxing-android-embedded:3.6.0'
}
  1. 在布局文件中添加 SurfaceView 和 TextView:
<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <SurfaceView
        android:id="@+id/surface_view"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"/>

    <TextView
        android:id="@+id/result_text"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:padding="10dp"
        android:textColor="#000000"
        android:textSize="18sp"
        android:textStyle="bold"/>
        
</LinearLayout>
  1. 在 Java 代码中初始化和启动扫描器:
public class MainActivity extends AppCompatActivity implements ZXingScannerView.ResultHandler {

    private ZXingScannerView mScannerView;
    private TextView mResultTextView;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        mResultTextView = findViewById(R.id.result_text);
        
        mScannerView = new ZXingScannerView(this);
        mScannerView.setResultHandler(this);
        
        LinearLayout layout = findViewById(R.id.layout);
        layout.addView(mScannerView);
    }

    @Override
    public void onResume() {
        super.onResume();
        mScannerView.startCamera();
    }

    @Override
    public void onPause() {
        super.onPause();
        mScannerView.stopCamera();
    }

    @Override
    public void handleResult(Result result) {
        mResultTextView.setText(result.getText());
        mScannerView.resumeCameraPreview(this);
    }
}
  1. 生成二维码:
String content = "https://www.example.com";
Bitmap bitmap = encodeAsBitmap(content);

private Bitmap encodeAsBitmap(String content) {
    BitMatrix result;
    try {
        result = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, 500, 500, null);
    } catch (WriterException e) {
        e.printStackTrace();
        return null;
    }
    int width = result.getWidth();
    int height = result.getHeight();
    int[] pixels = new int[width * height];
    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) ? Color.BLACK : Color.WHITE;
        }
    }
    Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
    bitmap.setPixels(pixels, 0, width, 0, 0, width, height);
    return bitmap;
}
``
android 如何生成二维码

原文地址: https://www.cveoy.top/t/topic/eEV8 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录