Android -- 生成二维码
16lz
2021-01-23
直接上代码:
public class MainActivity extends Activity { private TextView tv; private ImageView iv; private int QR_WIDTH, QR_HEIGHT; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); tv = (TextView) findViewById(R.id.tv); iv = (ImageView) findViewById(R.id.iv); QR_WIDTH = 300; QR_HEIGHT = 300; createImage(); } // 生成QR图 private void createImage() { try { // 需要引入core包 QRCodeWriter writer = new QRCodeWriter(); String text = tv.getText().toString(); if (text == null || "".equals(text) || text.length() < 1) { return; } // 把输入的文本转为二维码 BitMatrix martix = writer.encode(text, BarcodeFormat.QR_CODE, QR_WIDTH, QR_HEIGHT); Hashtable<EncodeHintType, String> hints = new Hashtable<EncodeHintType, String>(); hints.put(EncodeHintType.CHARACTER_SET, "utf-8"); BitMatrix bitMatrix = new QRCodeWriter().encode(text, BarcodeFormat.QR_CODE, QR_WIDTH, QR_HEIGHT, hints); int[] pixels = new int[QR_WIDTH * QR_HEIGHT]; for (int y = 0; y < QR_HEIGHT; y++) { for (int x = 0; x < QR_WIDTH; x++) { if (bitMatrix.get(x, y)) { pixels[y * QR_WIDTH + x] = 0xff000000; } else { pixels[y * QR_WIDTH + x] = 0xffffffff; } } } Bitmap bitmap = Bitmap.createBitmap(QR_WIDTH, QR_HEIGHT, Bitmap.Config.ARGB_8888); bitmap.setPixels(pixels, 0, QR_WIDTH, 0, 0, QR_WIDTH, QR_HEIGHT); iv.setImageBitmap(bitmap); } catch (WriterException e) { e.printStackTrace(); } }}
要注意,需要导入一个core.jar包。见附件
更多相关文章
- Android(Java):jni源代码
- Android重启应用程序代码
- Android实现手机定位的案例代码
- Android写文件到SDCard的简单代码
- Android手电筒小程序实现代码
- Android中通过代码检测系统是否有root权限
- Android 代码片段---获取手机通讯录列表