欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

Android仿微信二维码和条形码

程序员文章站 2024-03-04 17:58:41
本文实例为大家分享了android仿微信二维码和条形码的具体代码,供大家参考,具体内容如下 package your.qrcode.namespace; i...

本文实例为大家分享了android仿微信二维码和条形码的具体代码,供大家参考,具体内容如下

package your.qrcode.namespace;

import java.io.file;
import java.io.fileoutputstream;
import java.util.hashmap;
import java.util.map;

import com.google.zxing.barcodeformat;
import com.google.zxing.encodehinttype;
import com.google.zxing.multiformatwriter;
import com.google.zxing.writerexception;
import com.google.zxing.common.bitmatrix;
import com.google.zxing.qrcode.decoder.errorcorrectionlevel;
import android.app.activity;
import android.content.context;
import android.graphics.bitmap;
import android.graphics.bitmap.config;
import android.graphics.bitmapfactory;
import android.graphics.canvas;
import android.graphics.color;
import android.graphics.matrix;
import android.graphics.pointf;
import android.graphics.rect;
import android.graphics.drawable.bitmapdrawable;
import android.os.bundle;
import android.os.environment;
import android.util.log;
import android.view.gravity;
import android.view.view;
import android.view.view.measurespec;
import android.view.viewgroup.layoutparams;
import android.widget.button;
import android.widget.imageview;
import android.widget.linearlayout;
import android.widget.textview;

public class qrcodetextactivityactivity extends activity {
 /** called when the activity is first created. */
 button btn1 = null;
 button btn2 = null;
 imageview ivimageview = null;

 @override
 public void oncreate(bundle savedinstancestate) {
 super.oncreate(savedinstancestate);
 setcontentview(r.layout.main);
 btn1 = (button) findviewbyid(r.id.button1);// 条形码
 btn2 = (button) findviewbyid(r.id.button2);// 二维码
 ivimageview = (imageview) findviewbyid(r.id.imageview1);
 final string strcontestring = "c2b0f58a6f09cafd1503c06ef08ac7aeb7ddb91a602dac145551c102143e6159e385cdc294";

 btn1.setonclicklistener(new view.onclicklistener() {
  public void onclick(view v) {
  bitmap mbitmap = null;
  mbitmap = creatbarcode(qrcodetextactivityactivity.this,
   strcontestring, 300, 300, true);
  if (mbitmap != null) {
   ivimageview.setimagebitmap(mbitmap);
  }
  }
 });
 btn2.setonclicklistener(new view.onclicklistener() {
  public void onclick(view v) {
  bitmap mbitmap = null;
  try {
   if (!strcontestring.equals("")) {
   mbitmap = create2dcode(strcontestring);

   // bitmap bm =
   // bitmapfactory.decoderesource(getresources(),
   // r.drawable.diagnose1);
   ivimageview.setimagebitmap(createbitmap(
    mbitmap,
    zoombitmap(bitmapfactory.decoderesource(
     getresources(), r.drawable.cccc), 100,100)));
   }
  } catch (exception e) {
   e.printstacktrace();
  }
  }
 });
 }

 public bitmap create2dcode(string str) throws writerexception {
 map<encodehinttype, object> hints = new hashmap<encodehinttype, object>();
 hints.put(encodehinttype.error_correction, errorcorrectionlevel.l);
 hints.put(encodehinttype.character_set, "gbk");
 // hints.put(encodehinttype.character_set, "utf-8");
 // 生成二维矩阵,编码时指定大小,不要生成了图片以后再进行缩放,这样会模糊导致识别失败
 bitmatrix matrix = new multiformatwriter().encode(str,
  barcodeformat.qr_code, 500, 500, hints);
 int width = matrix.getwidth();
 int height = matrix.getheight();
 // 二维矩阵转为一维像素数组,也就是一直横着排了
 int[] pixels = new int[width * height];
 for (int i = 0; i < pixels.length; i++) {
  pixels[i] = 0xffffffff;
 }
 for (int y = 0; y < height; y++) {
  for (int x = 0; x < width; x++) {
  if (matrix.get(x, y)) {
   pixels[y * width + x] = 0xff000000;
  }
  }
 }
 bitmap bitmap = bitmap.createbitmap(width, height,
  bitmap.config.argb_8888);
 // 通过像素数组生成bitmap,具体参考api
 bitmap.setpixels(pixels, 0, width, 0, 0, width, height);
 return bitmap;
 }

 public file getcodepath(string name) {
 string extern_path = null;
 if (environment.getexternalstoragestate().equals(
  environment.media_mounted) == true) {
  extern_path = android.os.environment.getexternalstoragedirectory()
   .getabsolutepath() + "/";
  file f = new file(extern_path);
  if (!f.exists()) {
  f.mkdirs();
  }
 }
 return new file(extern_path + name);
 }

 /**
 * 图片两端所保留的空白的宽度
 */
 private int marginw = 20;
 /**
 * 条形码的编码类型
 */
 private barcodeformat barcodeformat = barcodeformat.code_128;

 /**
 * 生成条形码
 * 
 * @param context
 * @param contents
 *      需要生成的内容
 * @param desiredwidth
 *      生成条形码的宽带
 * @param desiredheight
 *      生成条形码的高度
 * @param displaycode
 *      是否在条形码下方显示内容
 * @return
 */
 public bitmap creatbarcode(context context, string contents,
  int desiredwidth, int desiredheight, boolean displaycode) {
 bitmap ruseltbitmap = null;
 if (displaycode) {
  bitmap barcodebitmap = encodeasbitmap(contents, barcodeformat,
   desiredwidth, desiredheight);
  bitmap codebitmap = creatcodebitmap(contents, desiredwidth + 2
   * marginw, desiredheight, context);
  ruseltbitmap = mixturebitmap(barcodebitmap, codebitmap, new pointf(
   0, desiredheight));
 } else {
  ruseltbitmap = encodeasbitmap(contents, barcodeformat,
   desiredwidth, desiredheight);
 }

 return ruseltbitmap;
 }

 /**
 * 生成显示编码的bitmap
 * 
 * @param contents
 * @param width
 * @param height
 * @param context
 * @return
 */
 protected bitmap creatcodebitmap(string contents, int width, int height,
  context context) {
 textview tv = new textview(context);
 linearlayout.layoutparams layoutparams = new linearlayout.layoutparams(
  layoutparams.fill_parent, layoutparams.wrap_content);
 tv.setlayoutparams(layoutparams);
 tv.settext(contents);
 tv.setheight(height);
 tv.setgravity(gravity.center_horizontal);
 tv.setwidth(width);
 tv.setdrawingcacheenabled(true);
 tv.settextcolor(color.black);
 tv.measure(measurespec.makemeasurespec(0, measurespec.unspecified),
  measurespec.makemeasurespec(0, measurespec.unspecified));
 tv.layout(0, 0, tv.getmeasuredwidth(), tv.getmeasuredheight());

 tv.builddrawingcache();
 bitmap bitmapcode = tv.getdrawingcache();
 return bitmapcode;
 }

 /**
 * 生成条形码的bitmap
 * 
 * @param contents
 *      需要生成的内容
 * @param format
 *      编码格式
 * @param desiredwidth
 * @param desiredheight
 * @return
 * @throws writerexception
 */
 protected bitmap encodeasbitmap(string contents, barcodeformat format,
  int desiredwidth, int desiredheight) {
 final int white = 0xffffffff;
 final int black = 0xff000000;

 multiformatwriter writer = new multiformatwriter();
 bitmatrix result = null;
 try {
  result = writer.encode(contents, format, desiredwidth,
   desiredheight, null);
 } catch (writerexception e) {
  // todo auto-generated catch block
  e.printstacktrace();
 }

 int width = result.getwidth();
 int height = result.getheight();
 int[] pixels = new int[width * height];
 // all are 0, or black, by default
 for (int y = 0; y < height; y++) {
  int offset = y * width;
  for (int x = 0; x < width; x++) {
  pixels[offset + x] = result.get(x, y) ? black : white;
  }
 }

 bitmap bitmap = bitmap.createbitmap(width, height,
  bitmap.config.argb_8888);
 bitmap.setpixels(pixels, 0, width, 0, 0, width, height);
 return bitmap;
 }

 /**
 * 将两个bitmap合并成一个
 * 
 * @param first
 * @param second
 * @param frompoint
 *      第二个bitmap开始绘制的起始位置(相对于第一个bitmap)
 * @return
 */
 protected bitmap mixturebitmap(bitmap first, bitmap second, pointf frompoint) {
 if (first == null || second == null || frompoint == null) {
  return null;
 }
 bitmap newbitmap = bitmap.createbitmap(
  first.getwidth() + second.getwidth() + marginw,
  first.getheight() + second.getheight(), config.argb_4444);
 canvas cv = new canvas(newbitmap);
 cv.drawbitmap(first, marginw, 0, null);
 cv.drawbitmap(second, frompoint.x, frompoint.y, null);
 cv.save(canvas.all_save_flag);
 cv.restore();

 return newbitmap;
 }

 /*** 仿微信二维码开始 ***/
 // 图片剪切
 public bitmap cutbitmap(bitmap mbitmap, rect r, bitmap.config config) {
 int width = r.width();
 int height = r.height();
 bitmap croppedimage = bitmap.createbitmap(width, height, config);
 canvas cvs = new canvas(croppedimage);
 rect dr = new rect(0, 0, width, height);
 cvs.drawbitmap(mbitmap, r, dr, null);
 return croppedimage;
 }

 /***
 * 合并图片
 * 
 * @param src
 * @param watermark
 * @return
 */
 private bitmap createbitmap(bitmap src, bitmap watermark) {
 string tag = "createbitmap";
 log.d(tag, "create a new bitmap");
 if (src == null) {
  return null;
 }
 int w = src.getwidth();
 int h = src.getheight();
 int ww = watermark.getwidth();
 int wh = watermark.getheight();
 // create the new blank bitmap
 bitmap newb = bitmap.createbitmap(w, h, config.argb_8888);// 创建一个新的和src长度宽度一样的位图
 canvas cv = new canvas(newb);

 // draw src into
 cv.drawbitmap(src, 0, 0, null);// 在 0,0坐标开始画入src

 // 在src的中间画watermark
 cv.drawbitmap(watermark, w / 2 - ww / 2, h / 2 - wh / 2, null);// 设置ic_launcher的位置

 // save all clip
 cv.save(canvas.all_save_flag);// 保存
 // store
 cv.restore();// 存储
 return newb;
 }

 /***
 * 缩放图片
 * 
 * @param src
 * @param destwidth
 * @param destheigth
 * @return
 */
 private bitmap zoombitmap(bitmap src, int destwidth, int destheigth) {
 string tag = "lessenbitmap";
 if (src == null) {
  return null;
 }
 int w = src.getwidth();// 源文件的大小
 int h = src.getheight();
 // calculate the scale - in this case = 0.4f
 float scalewidth = ((float) destwidth) / w;// 宽度缩小比例
 float scaleheight = ((float) destheigth) / h;// 高度缩小比例
 log.d(tag, "bitmap width is :" + w);
 log.d(tag, "bitmap height is :" + h);
 log.d(tag, "new width is :" + destwidth);
 log.d(tag, "new height is :" + destheigth);
 log.d(tag, "scale width is :" + scalewidth);
 log.d(tag, "scale height is :" + scaleheight);
 matrix m = new matrix();// 矩阵
 m.postscale(scalewidth, scaleheight);// 设置矩阵比例
 bitmap resizedbitmap = bitmap.createbitmap(src, 0, 0, w, h, m, true);// 直接按照矩阵的比例把源文件画入进行
 return resizedbitmap;
 }

}

<?xml version="1.0" encoding="utf-8"?>
<linearlayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent"
  android:orientation="vertical" android:background="#ffffff">

  <textview
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="@string/hello" />

  <button
    android:id="@+id/button1"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="条形码" />


  <button
    android:id="@+id/button2"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="二维码" />


  <relativelayout
    android:layout_width="match_parent"
    android:layout_height="match_parent" >


    <imageview
      android:id="@+id/imageview1"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_centerhorizontal="true"
      android:layout_centervertical="true"
      android:scaletype="fitxy"
      android:src="@drawable/ic_launcher" />

  </relativelayout>

</linearlayout>

图片美工做下处理。貌似需要做一个描边。png透明背景 

Android仿微信二维码和条形码

在加两个方法

/***
 * 缩放图片并加描边
 * 
 * @param src
 * @param destwidth
 * @param destheigth
 * @return
 */
 private bitmap zoombitmapborder(bitmap src, int destwidth, int destheigth) {
 string tag = "lessenbitmap";
 if (src == null) {
  return null;
 }
 int w = src.getwidth();// 源文件的大小
 int h = src.getheight();
 // calculate the scale - in this case = 0.4f
 float scalewidth = ((float) destwidth - 4) / w;// 宽度缩小比例
 float scaleheight = ((float) destheigth - 4) / h;// 高度缩小比例
 log.d(tag, "bitmap width is :" + w);
 log.d(tag, "bitmap height is :" + h);
 log.d(tag, "new width is :" + destwidth);
 log.d(tag, "new height is :" + destheigth);
 log.d(tag, "scale width is :" + scalewidth);
 log.d(tag, "scale height is :" + scaleheight);
 matrix m = new matrix();// 矩阵
 m.postscale(scalewidth, scaleheight);// 设置矩阵比例
 bitmap resizedbitmap = bitmap.createbitmap(src, 0, 0, w, h, m, true);// 直接按照矩阵的比例把源文件画入进行

 bitmap newb = bitmap.createbitmap(destwidth, destheigth,
  config.argb_8888);// 创建一个新的和src长度宽度一样的位图
 canvas cv = new canvas(newb);
 //cv.drawcolor(r.color.white);
cv.drawrgb(0,128,128);
 cv.drawbitmap(resizedbitmap, 2, 2, null);// 设置ic_launcher的位置

 // save all clip
 cv.save(canvas.all_save_flag);// 保存
 // store
 cv.restore();// 存储

 return getroundedcornerbitmap(newb);
 }

 /**
 * 图片圆角
 * @param bitmap
 * @return
 */
 public static bitmap getroundedcornerbitmap(bitmap bitmap) {
 bitmap output = bitmap.createbitmap(bitmap.getwidth(),
  bitmap.getheight(), config.argb_8888);
 canvas canvas = new canvas(output);
 final int color = 0xff424242;
 final paint paint = new paint();
 final rect rect = new rect(0, 0, bitmap.getwidth(), bitmap.getheight());
 final rectf rectf = new rectf(rect);
 final float roundpx = 12;
 paint.setantialias(true);
 canvas.drawargb(0, 0, 0, 0);
 paint.setcolor(color);
 canvas.drawroundrect(rectf, roundpx, roundpx, paint);
 paint.setxfermode(new porterduffxfermode(mode.src_in));
 canvas.drawbitmap(bitmap, rect, rect, paint);
 return output;

 }

Android仿微信二维码和条形码

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。