/**
* 生成二维码Bitmap的静态方法
*
* @param str
* 待编码的字符串
* @param width
* 生成二维码的宽度
* @param height
* 生成二维码的高度
* @return
*/
public static Bitmap createQRCode(String str, int width, int height)
{
// 设置参数
Hashtable<EncodeHintType, Object> hints = new Hashtable<EncodeHintType, Object>();
hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
hints.put(EncodeHintType.MARGIN, 0);
BitMatrix matrix = null;
try
{
// 关键步骤,编码,返回BitMatrix
matrix = new MultiFormatWriter().encode(str, BarcodeFormat.QR_CODE,
width, height, hints);
}
catch (WriterException e)
{
e.printStackTrace();
}
// 存放像素的数组
int[] pixels = new int[width * height];
// 纵向,从第一行到最后一行的像素
for (int y = 0; y < height; y++)
{
// 横向
for (int x = 0; x < width; x++)
{
// 判断像素是否有值
if (matrix.get(x, y))
{
// 设置像素颜色
pixels[y * width + x] = Color.BLACK;
}
}
}
// 生成Bitmap
Bitmap bitmap = Bitmap.createBitmap(width, height,
Bitmap.Config.ARGB_8888);
bitmap.setPixels(pixels, 0, width, 0, 0, width, height);
// 返回Bitmap
return bitmap;
}