欢迎来到代码驿站!

Android代码

当前位置:首页 > 移动开发 > Android代码

Android二维码创建实例

时间:2020-12-09 21:35:10|栏目:Android代码|点击:

Android二维码之创建

实现效果图:

1.Android 有自带的jar包可以生成二维码core-3.0.0.jar,其中的com.google.zxing包

2.写一个二维码生成的工具类,网上搜的话应该一大堆。

实例代码:

package com.example.administrator.twocodedemo;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.PointF;
import android.view.Gravity;
import android.view.View.MeasureSpec;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.TextView;

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.QRCodeWriter;

import java.util.Hashtable;

/** 
*
*   生成条形码和二维码的工具
*/
public class ZXingUtils {
  /**
   * 生成二维码 要转换的地址或字符串,可以是中文
   * 
   * @param url
   * @param width
   * @param height
   * @return
   */
  public static Bitmap createQRImage(String url, final int width, final int height) {
    try {
      // 判断URL合法性
      if (url == null || "".equals(url) || url.length() < 1) {
        return null;
      }
      Hashtable<EncodeHintType, String> hints = new Hashtable<EncodeHintType, String>();
      hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
      // 图像数据转换,使用了矩阵转换
      BitMatrix bitMatrix = new QRCodeWriter().encode(url,
          BarcodeFormat.QR_CODE, width, height, hints);
      int[] pixels = new int[width * height];
      // 下面这里按照二维码的算法,逐个生成二维码的图片,
      // 两个for循环是图片横列扫描的结果
      for (int y = 0; y < height; y++) {
        for (int x = 0; x < width; x++) {
          if (bitMatrix.get(x, y)) {
            pixels[y * width + x] = 0xff000000;
          } else {
            pixels[y * width + x] = 0xffffffff;
          }
        }
      }
      // 生成二维码图片的格式,使用ARGB_8888
      Bitmap bitmap = Bitmap.createBitmap(width, height,
          Bitmap.Config.ARGB_8888);
      bitmap.setPixels(pixels, 0, width, 0, 0, width, height);
      return bitmap;
    } catch (WriterException e) {
      e.printStackTrace();
    }
    return null;
  }

  /**
   * 生成条形码
   *
   * @param context
   * @param contents
   *      需要生成的内容
   * @param desiredWidth
   *      生成条形码的宽带
   * @param desiredHeight
   *      生成条形码的高度
   * @param displayCode
   *      是否在条形码下方显示内容
   * @return
   */
  public static Bitmap creatBarcode(Context context, String contents,
                   int desiredWidth, int desiredHeight, boolean displayCode) {
    Bitmap ruseltBitmap = null;
    /**
     * 图片两端所保留的空白的宽度
     */
    int marginW = 20;
    /**
     * 条形码的编码类型
     */
    BarcodeFormat barcodeFormat = BarcodeFormat.CODE_128;

    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 format
   *      编码格式
   * @param desiredWidth
   * @param desiredHeight
   * @return
   * @throws WriterException
   */
  protected static 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 contents
   * @param width
   * @param height
   * @param context
   * @return
   */
  protected static Bitmap creatCodeBitmap(String contents, int width,
                      int height, Context context) {
    TextView tv = new TextView(context);
    LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
        LayoutParams.MATCH_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 first
   * @param second
   * @param fromPoint
   *      第二个Bitmap开始绘制的起始位置(相对于第一个Bitmap)
   * @return
   */
  protected static Bitmap mixtureBitmap(Bitmap first, Bitmap second,
                     PointF fromPoint) {
    if (first == null || second == null || fromPoint == null) {
      return null;
    }
    int marginW = 20;
    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;
  }

}
ZXingUtils

3.MainActivity

@OnClick({R.id.btn_create, R.id.iv_two_code}) 
  public void onClick(View view) { 
    switch (view.getId()) { 
      case R.id.btn_create: 
  
        String url = etUrl.getText().toString().trim(); 
        Bitmap bitmap = ZXingUtils.createQRImage(url, ivTwoCode.getWidth(), ivTwoCode.getHeight()); 
        ivTwoCode.setImageBitmap(bitmap); 

例如:

String company=etCompany.getText().toString().trim() ;
        String phone =etPhone .getText().toString().trim() ;
        String email = etEmail.getText().toString().trim() ;
        String web = etWeb.getText().toString().trim() ;
        //二维码中包含的文本信息
        String contents= "BEGIN:VCARD\nVERSION:3.0\nORG:"+company+"\nTEL:"+phone+"\nURL:"+web+"\nEMAIL:"+email+"\nEND:VCARD";
      try {
        //调用方法createCode生成二维码
    Bitmap bm=createCode(contents, logo, BarcodeFormat.QR_CODE);
    

感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!

上一篇:Android简易电话拨号器实例详解

栏    目:Android代码

下一篇:Android程序开发ListView+Json+异步网络图片加载+滚动翻页的例子(图片能缓存,图片不错乱)

本文标题:Android二维码创建实例

本文地址:http://www.codeinn.net/misctech/31148.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有