Android使用zxing生成二维码
效果图如下:
前提:导入zxing的jar后开始操作,老规矩最后有源码,作者布局默认相对布局。
第一步:定义二维码的长宽高及图片控件
第二步:实例化QRCodeWriter后利用for循环将二维码画出来,然后用图片控件加载图片。
源码如下:
布局文件:
<Button
android:id="@+id/mybutton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="0dp"
android:text="点击显示二维码"
android:textSize="20sp" />
<ImageView
android:id="@+id/imageView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="192dp"
android:src="@drawable/ic_launcher_background" />
<EditText
android:id="@+id/myeditText"
android:layout_width="300dp"
android:maxLines="1"
android:layout_height="wrap_content"
android:layout_below="@+id/mybutton"
android:layout_centerHorizontal="true"
android:ems="10"
android:hint="请输入要加载成二维码的内容" />
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
java文件:
public class MainActivity extends Activity implements View.OnClickListener {
private int width = 300;
private int height = 300;
private ImageView imageView;
private Bitmap bit;
private Button mybutton;
private EditText myeditText;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initView();
}
private void initView() {
imageView = (ImageView) findViewById(R.id.imageView);
mybutton = (Button) findViewById(R.id.mybutton);
mybutton.setOnClickListener(this);
myeditText = (EditText) findViewById(R.id.myeditText);
myeditText.setOnClickListener(this);
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.mybutton:
String name=myeditText.getText().toString();
if(name.equals("")){
myeditText.setError("请输入内容");
}else{
zxing(name);
}
break;
}
}
private void zxing(String name){
QRCodeWriter qrCodeWriter = new QRCodeWriter();
Map<EncodeHintType, String> hints = new HashMap<>();
hints.put(EncodeHintType.CHARACTER_SET, "utf-8"); //记得要自定义长宽
BitMatrix encode = null;
try {
encode = qrCodeWriter.encode(name, BarcodeFormat.QR_CODE, width, height, hints);
} catch (WriterException e) {
e.printStackTrace();
}
int[] colors = new int[width * height];
//利用for循环将要表示的信息写出来
for (int i = 0; i < width; i++) {
for (int j = 0; j < height; j++) {
if (encode.get(i, j)) {
colors[i * width + j] = Color.BLACK;
} else {
colors[i * width + j] = Color.WHITE;
}
}
}
bit = Bitmap.createBitmap(colors, width, height, Bitmap.Config.RGB_565);
imageView.setImageBitmap(bit);
}
}