android 生成二维码(带图片&不带图片),深入浅出Androi

80 阅读1分钟

}

2、生成带图片的二维码

===========

/**

  • @Title: createQRImage带图片

  • @param url

  •        可以是链接地址,也可以是文字
    
  • @param QR_WIDTH

  •        二维码宽度
    
  • @param QR_HEIGHT

  •        二维码高度
    
  • @param mBitmap

  •        图片
    
  • @return Bitmap 返回一个bitmap,可以自行保存到本地,也可以设置显示在页面

*/

public static Bitmap createQRImage(String url, int QR_WIDTH, int QR_HEIGHT,

Bitmap mBitmap,Context context) {

try {

Matrix m = new Matrix();

float sx = (float) 2 * IMAGE_HALFWIDTH / mBitmap.getWidth();

float sy = (float) 2 * IMAGE_HALFWIDTH

/ mBitmap.getHeight();

m.setScale(sx, sy);

mBitmap = Bitmap.createBitmap(mBitmap, 0, 0,

mBitmap.getWidth(), mBitmap.getHeight(), m, false);

String contentString = url;

mBitmap = cretaeBitmap(mBitmap,new String(contentString.getBytes(),"utf-8"),context);

} catch (UnsupportedEncodingException e) {

// TODO Auto-generated catch block

e.printStackTrace();

} catch (WriterException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

return mBitmap;

}

private static final int IMAGE_HALFWIDTH = 40;//二维码的宽度

public static Bitmap cretaeBitmap(Bitmap mBitmap,String str,Context context) throws WriterException {

Hashtable<EncodeHintType, Object> hints = new Hashtable<EncodeHintType, Object>();

hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);

hints.put(EncodeHintType.CHARACTER_SET, "utf-8");

hints.put(EncodeHintType.MARGIN, 1);

BitMatrix matrix = new MultiFormatWriter().encode(str,

BarcodeFormat.QR_CODE, Utils.dip2px(context, 300), Utils.dip2px(context, 300), hints);

int width = matrix.getWidth();

int height = matrix.getHeight();

int halfW = width / 2;

int halfH = height / 2;

int[] pixels = new int[width * height];

for (int y = 0; y < height; y++) {

for (int x = 0; x < width; x++) {

if (x > halfW - IMAGE_HALFWIDTH && x < halfW + IMAGE_HALFWIDTH

&& y > halfH - IMAGE_HALFWIDTH

&& y < halfH + IMAGE_HALFWIDTH) {

pixels[y * width + x] = mBitmap.getPixel(x - halfW

  • IMAGE_HALFWIDTH, y - halfH + IMAGE_HALFWIDTH);

} else {

if (matrix.get(x, y)) {

pixels[y * width + x] = 0xff000000;

} else {

pixels[y * width + x] = 0xffffffff;

}

}

}

}

Bitmap bitmap = Bitmap.createBitmap(width, height,

Bitmap.Config.ARGB_8888);

bitmap.setPixels(pixels, 0, width, 0, 0, width, height);

总结

最后小编想说:不论以后选择什么方向发展,目前重要的是把Android方面的技术学好,毕竟其实对于程序员来说,要学习的知识内容、技术有太多太多,要想不被环境淘汰就只有不断提升自己,从来都是我们去适应环境,而不是环境来适应我们!

这里附上我整理的几十套腾讯、字节跳动,京东,小米,头条、阿里、美团等公司19年的Android面试题。把技术点整理成了视频和PDF(实际上比预期多花了不少精力),包含知识脉络 + 诸多细节。

由于篇幅有限,这里以图片的形式给大家展示一小部分。

详细整理在GitHub可以见;

Android架构视频+BAT面试专题PDF+学习笔记

网上学习 Android的资料一大堆,但如果学到的知识不成体系,遇到问题时只是浅尝辄止,不再深入研究,那么很难做到真正的技术提升。希望这份系统化的技术体系对大家有一个方向参考。

技术进阶之路很漫长,一起共勉吧~