Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> 關於Android編程 >> Android仿微信二維碼和條形碼

Android仿微信二維碼和條形碼

編輯:關於Android編程

本文實例為大家分享了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透明背景 

在加兩個方法

/***
 * 縮放圖片並加描邊
 * 
 * @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;

 }

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持本站。

  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved