大家可以直接复制粘贴,运行之后再根据需要更改
https://pan.baidu.com/s/1hr9L5cw 这个是下载 zxing-core-3.2.0.jar包的地址. (网上很多提供下载的貌似都是要积分什么的,很烦.)
//显示二维码的Activity
package com.app222.cn; import android.graphics.Bitmap; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.util.DisplayMetrics; import android.view.View; import android.widget.ImageView; import com.google.zxing.WriterException; /** * 二维码生成 */ public class MainActivity extends AppCompatActivity { private ImageView iv_qr_image; protected int mScreenWidth ; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); iv_qr_image = (ImageView)findViewById(R.id.iv_qr_image); DisplayMetrics dm = new DisplayMetrics(); getWindowManager().getDefaultDisplay().getMetrics(dm); mScreenWidth = dm.widthPixels; } //生成二维码 public void Create2QR(View v){ String uri = "http://blog.csdn.net/yanfarong";
Bitmap bitmap; try { bitmap = BitmapUtil.createQRCode(uri, mScreenWidth); if(bitmap != null){ iv_qr_image.setImageBitmap(bitmap); } } catch (WriterException e) { e.printStackTrace(); } } }
//布局文件<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:background="@android:color/white" android:orientation="vertical" > <Button android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_marginTop="30dp" android:onClick="Create2QR" android:text="生成二维码" /> <ImageView android:id="@+id/iv_qr_image" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center" /> </LinearLayout>
//工具类
package com.app222.cn; import java.util.Hashtable; import android.graphics.Bitmap; import android.util.Log; 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; public class BitmapUtil {
private static final int BLACK = 0xff000000; /** * 生成一个二维码图像 * @param url 传入的字符串,通常是一个URL * @param widthAndHeight 图像的宽高 * @return */ public static Bitmap createQRCode(String str, int widthAndHeight) throws WriterException { Hashtable<EncodeHintType, String> hints = new Hashtable<EncodeHintType, String>(); hints.put(EncodeHintType.CHARACTER_SET, "utf-8"); BitMatrix matrix = new MultiFormatWriter().encode(str, BarcodeFormat.QR_CODE, widthAndHeight, widthAndHeight); int width = matrix.getWidth(); int height = matrix.getHeight(); int[] pixels = new int[width * height]; for (int y = 0; y < height; y++) { for (int x = 0; x < width; x++) { if (matrix.get(x, y)) { pixels[y * width + x] = BLACK; } } } Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888); bitmap.setPixels(pixels, 0, width, 0, 0, width, height); return bitmap; } }