本文主要是介绍**利用Zxing生成二维码,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
利用Zxing生成二维码:
一、导入Zxing
二、下面是代码
package com.qf.qrcodescan;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.ImageView;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import java.util.HashMap;
public class MainActivity extends AppCompatActivity {
private ImageView imageView;@Override
protected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);imageView = (ImageView) findViewById(R.id.img);
}public void Qrcode(View view) {String msg = "光头强";createCode(msg);System.out.println("=====生成========");}private static final int BLACK=0xFF000000,WHITE=0xFFFFFFFF;public void createCode(String msg){//二维码大小int ret = 512;//生成所需要的配置HashMap<EncodeHintType,Object> hints = new HashMap<>();//设置二维码编码hints.put(EncodeHintType.CHARACTER_SET,"UTF-8");//二维码容错级别hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);QRCodeWriter writer = new QRCodeWriter();try {//矩阵BitMatrix encode = writer.encode(msg, BarcodeFormat.QR_CODE, ret, ret, hints);int width = encode.getWidth();int height = encode.getHeight();//创建数组 用于存储 像素点int[] pixles = new int[width*height];//整理图形像素数据for (int y=0;y<height;y++){int offset = y*width;for (int x=0;x<width;x++){pixles[offset+x] = encode.get(x,y)?BLACK:WHITE;}}Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);bitmap.setPixels(pixles,0,width,0,0,width,height);if(bitmap!=null){Bitmap icon = BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher);bitmap = createIconCode(bitmap, icon);}imageView.setImageBitmap(bitmap);} catch (WriterException e) {e.printStackTrace();}
}private Bitmap createIconCode(Bitmap code, Bitmap icon) {int codeWidth = code.getWidth();int codeHeight = code.getHeight();int iconWidth = icon.getWidth();int iconHeight = icon.getHeight();//比例float scales = codeWidth * 1.0f / 5 / iconWidth;//创建个 空图片Bitmap bitmap = Bitmap.createBitmap(codeWidth, codeHeight, Bitmap.Config.ARGB_8888);//在空图片上面创建画布Canvas canvas = new Canvas(bitmap);canvas.drawBitmap(code,0,0,null);//缩放画布canvas.scale(scales,scales,codeWidth/2,codeHeight/2);canvas.drawBitmap(icon,codeWidth/2-iconWidth/2,codeHeight/2-iconHeight/2,null);canvas.save(Canvas.ALL_SAVE_FLAG);canvas.restore();return bitmap;
}
}
这篇关于**利用Zxing生成二维码的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!