Android应用开发:生成二维码

fydxdk 9年前

   二维码这个东西自从出来后就一直流行到现在,无论走到哪里,二维码都可能出现在你的眼前。现在智能手机基本上都有扫一扫功能,扫的就是二维码。那我们怎么样在手机上生成个自己的二维码呢?Android开发中生成二维码不难,用Google ZXing生成二维码很简单,下面我们就简单操作一直,把最主要的代码贴出来,还请大家多指教!

第一步:

 确定我们二维码的位置,即是在我们应用的哪个页面的哪个位置,简单讲就是用一个ImageView把二维码展示出来,我们就把二维码展示在下面布局activity_qr_layout中的ImageView上:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

    xmlns:sample="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#dadada"
    android:focusable="true"
    android:focusableInTouchMode="true"
    android:orientation="vertical" >

            <ImageView 
                android:id="@+id/qr_show"
                android:layout_gravity="center_horizontal"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginBottom="55dp"
                android:scaleType="fitXY"
                android:background="@null"
                android:src="@drawable/default_pic"
                />
</LinearLayout>

接下来直接在Activity中生成二维码就可以了:

public class MyQrActivity extends Activity {

private ImageView qr_show;
private SampleListLinearLayout lv_record;

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

protected void initViews() {

qr_show = (ImageView) findViewById(R.id.qr_show);

DisplayMetrics outMetrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(outMetrics);
int w = outMetrics.widthPixels * 8 / 11;//设置宽度
ViewGroup.LayoutParams layoutParams = qr_show.getLayoutParams();
layoutParams.height = layoutParams.width = w;//设置高度
qr_show.setLayoutParams(layoutParams);

try {
Bitmap bitmap = QRUtils.encodeToQRWidth("http://write.blog.csdn.net/", w);//要生成二维码的内容,我这就是一个网址
qr_show.setImageBitmap(bitmap);
}
catch (Exception e) {
e.printStackTrace();
Toast.makeText(this, "生成二维码失败", Toast.LENGTH_SHORT);
}
}
}

下面是生成二维码的工具类,不要忘记在项目中要导入ZXing相关的jar包:

public class QRUtils {
private static final int WHITE = 0xFFFFFFFF;
    private static final int BLACK = 0xFF000000;
    /**
     * 将字符串按照指定大小生成二维码图片
     */
public static Bitmap encodeToQR(String contentsToEncode, int dimension) throws Exception{
if(TextUtils.isEmpty(contentsToEncode))
return null;

    BarcodeFormat format = BarcodeFormat.QR_CODE;
    Map<EncodeHintType,Object> hints = new EnumMap<EncodeHintType,Object>(EncodeHintType.class);
    hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
    BitMatrix result = new MultiFormatWriter().encode(contentsToEncode, format, dimension, dimension, hints);
    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) ? BLACK : WHITE;
          }
        }


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

public static Bitmap encodeToQRWidth(String contentsToEncode, int dimension) throws Exception{
if(TextUtils.isEmpty(contentsToEncode))
return null;

BarcodeFormat format = BarcodeFormat.QR_CODE;
    Map<EncodeHintType,Object> hints = new EnumMap<EncodeHintType,Object>(EncodeHintType.class);
    hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
    BitMatrix result = new MultiFormatWriter().encode(contentsToEncode, format, dimension, dimension, hints);
int width = result.getWidth();
int height = result.getHeight();

boolean isFirstBlack = true;
int startX = 0;
int startY = 0;

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) ? BLACK : WHITE;
if(result.get(x, y) && isFirstBlack){
isFirstBlack = false;
startX = x;
startY = y;
}
}
}
Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
        bitmap.setPixels(pixels, 0, width, 0, 0, width, height);
        
        Matrix m = new Matrix();
float sx = (width + 2f*startX) / width;
float sy = (height + 2f*startY) / height;
m.postScale(sx, sy);

Bitmap qrBitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(qrBitmap);
canvas.translate(-startX, -startY);

Paint paint = new Paint();
paint.setAntiAlias(true);

canvas.drawBitmap(bitmap, m, paint);
        canvas.save();
        
        return qrBitmap;
}
}

ok搞定,拿去扫一扫就可以啦!