Android加载二维码
效果图
布局文件中添加ImageView组件,用来存放二维码
public class ErWeiMa extends BaseActivity {
private ImageView imageView4;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
initView();
}
private void initView() {
imageView4 = findViewById(R.id.imageView4);
Bitmap bitmap = setBitMap("I love you", 400, 400);
imageView4.setImageBitmap(bitmap);
}
public Bitmap setBitMap(String string, int width, int height) {
QRCodeWriter writer = new QRCodeWriter();
Map<EncodeHintType, String> map = new HashMap<>();
map.put(EncodeHintType.CHARACTER_SET, "utf-8");
try {
BitMatrix encode = writer.encode(string, BarcodeFormat.QR_CODE, width, height, map);
int[] ints = new int[width * height];
for (int i = 0; i < width; i++) {
for (int j = 0; j < height; j++) {
if (encode.get(i, j)) {
ints[i * width + j] = 0x00000000;
} else {
ints[i * width + j] = 0xffffffff;
}
}
}
return Bitmap.createBitmap(ints, 0, width, width, height, Bitmap.Config.RGB_565);
} catch (WriterException e) {
e.printStackTrace();
}
return null;
}
@Override
protected int getLayout() {
return R.layout.activity_erweima;
}
}