Android應用開發:生成二維碼

f663x 9年前發布 | 5K 次閱讀 Java Android

     二維碼這個東西自從出來后就一直流行到現在,無論走到哪里,二維碼都可能出現在你的眼前。現在智能手機基本上都有掃一掃功能,掃的就是二維碼。那我們怎 么樣在手機上生成個自己的二維碼呢?Android開發中生成二維碼不難,用Google ZXing生成二維碼很簡單,下面我們就簡單操作一直,把最主要的代碼貼出來,還請大家多指教!

第一步:

 確定我們二維碼的位置,即是在我們應用的哪個頁面的哪個位置,簡單講就是用一個ImageView把二維碼展示出來,我們就把二維碼展示在下面布局activity_qr_layout中的ImageView上:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

    xmlns:sample="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#dadada"
    android:focusable="true"
    android:focusableInTouchMode="true"
    android:orientation="vertical" >

            <ImageView 
                android:id="@+id/qr_show"
                android:layout_gravity="center_horizontal"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginBottom="55dp"
                android:scaleType="fitXY"
                android:background="@null"
                android:src="@drawable/default_pic"
                />
</LinearLayout>


接下來直接在Activity中生成二維碼就可以了:


public class MyQrActivity extends Activity {

private ImageView qr_show;
private SampleListLinearLayout lv_record;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_qr_layout);
 initViews();
}

protected void initViews() {

qr_show = (ImageView) findViewById(R.id.qr_show);

DisplayMetrics outMetrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(outMetrics);
int w = outMetrics.widthPixels * 8 / 11;//設置寬度
ViewGroup.LayoutParams layoutParams = qr_show.getLayoutParams();
layoutParams.height = layoutParams.width = w;//設置高度
qr_show.setLayoutParams(layoutParams);

try {
Bitmap bitmap = QRUtils.encodeToQRWidth("http://write.blog.csdn.net/", w);//要生成二維碼的內容,我這就是一個網址
qr_show.setImageBitmap(bitmap);
}
catch (Exception e) {
e.printStackTrace();
Toast.makeText(this, "生成二維碼失敗", Toast.LENGTH_SHORT);
}
}
}


下面是生成二維碼的工具類,不要忘記在項目中要導入ZXing相關的jar包:


public class QRUtils {
private static final int WHITE = 0xFFFFFFFF;
    private static final int BLACK = 0xFF000000;
    /**
     * 將字符串按照指定大小生成二維碼圖片
     */
public static Bitmap encodeToQR(String contentsToEncode, int dimension) throws Exception{
if(TextUtils.isEmpty(contentsToEncode))
return null;

    BarcodeFormat format = BarcodeFormat.QR_CODE;
    Map<EncodeHintType,Object> hints = new EnumMap<EncodeHintType,Object>(EncodeHintType.class);
    hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
    BitMatrix result = new MultiFormatWriter().encode(contentsToEncode, format, dimension, dimension, hints);
    int width = result.getWidth();
        int height = result.getHeight();
        int[] pixels = new int[width * height];
        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;
}

public static Bitmap encodeToQRWidth(String contentsToEncode, int dimension) throws Exception{
if(TextUtils.isEmpty(contentsToEncode))
return null;

BarcodeFormat format = BarcodeFormat.QR_CODE;
    Map<EncodeHintType,Object> hints = new EnumMap<EncodeHintType,Object>(EncodeHintType.class);
    hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
    BitMatrix result = new MultiFormatWriter().encode(contentsToEncode, format, dimension, dimension, hints);
int width = result.getWidth();
int height = result.getHeight();

boolean isFirstBlack = true;
int startX = 0;
int startY = 0;

int[] pixels = new int[width * height];
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;
if(result.get(x, y) && isFirstBlack){
isFirstBlack = false;
startX = x;
startY = y;
}
}
}
Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
        bitmap.setPixels(pixels, 0, width, 0, 0, width, height);

        Matrix m = new Matrix();
float sx = (width + 2f*startX) / width;
float sy = (height + 2f*startY) / height;
m.postScale(sx, sy);

Bitmap qrBitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(qrBitmap);
canvas.translate(-startX, -startY);

Paint paint = new Paint();
paint.setAntiAlias(true);

canvas.drawBitmap(bitmap, m, paint);
        canvas.save();

        return qrBitmap;
}
}


ok搞定,拿去掃一掃就可以啦!

 本文由用戶 f663x 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!