您的位置:首页 > 移动开发 > Android开发

Android 二维码快速生成代码

2014-11-25 17:17 357 查看
<pre name="code" class="java">看了很多人在找关于二维码生成的代码 今天就抽时间写了一下,希望对大家有所帮助!
<a target=_blank href="http://download.csdn.net/download/u012974916/8197269" target="_blank">点击打开链接</a>
public class MainActivity extends Activity {

private static final String TAG=MainActivity.class.getSimpleName();
private TextView qr_text;
private ImageView qr_image;

private final int QR_WIDTH=140;
private final int QR_HEIGHT=140;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
qr_text=(TextView) findViewById(R.id.textView1);
qr_image=(ImageView) findViewById(R.id.imageView1);
createImage();
}

// 生成QR图
private void createImage() {
try {
// 需要引入core包
QRCodeWriter writer = new QRCodeWriter();

String text = qr_text.getText().toString();
text="黄明明";
Log.i(TAG, "生成的文本:" + text);
if (text == null || "".equals(text) || text.length() < 1) {
return;
}

// 把输入的文本转为二维码
BitMatrix martix = writer.encode(text, BarcodeFormat.QR_CODE,
QR_WIDTH, QR_HEIGHT);

System.out.println("w:" + martix.getWidth() + "h:"
+ martix.getHeight());

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);
qr_image.setImageBitmap(bitmap);

} catch (WriterException e) {
e.printStackTrace();
}
}
}
布局文件记得自己写哦哦!!!
http://download.csdn.net/download/u012974916/8197269


                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: