<ImageView
android:id="@+id/code"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:text="@string/hello_world" />
</RelativeLayout></pre>
MainActivity
package com.example;
import java.util.Hashtable;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.os.Bundle;
import android.widget.ImageView;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;
public class MainActivity extends Activity {
private ImageView code;
private final int QR_WIDTH=300;
private final int QR_HEIGHT=300;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
code=(ImageView) findViewById(R.id.code);
createImage("weixin") ;
}
// 生成QR圖
private void createImage(String text) {
try {
// 需要引入core包
QRCodeWriter writer = new QRCodeWriter();
// 把輸入的文本轉為二維碼
BitMatrix martix = writer.encode(text, BarcodeFormat.QR_CODE,
QR_WIDTH, QR_HEIGHT);
//圖像數據轉換,使用了矩陣轉換
Hashtable<EncodeHintType, String> hints = new Hashtable<EncodeHintType, String>();
hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
BitMatrix bitMatrix = new QRCodeWriter().encode(text,
BarcodeFormat.QR_CODE, QR_WIDTH, QR_HEIGHT, hints);
int[] pixels = new int[QR_WIDTH * QR_HEIGHT];
for (int y = 0; y < QR_HEIGHT; y++) {
//下面這里按照二維碼的算法,逐個生成二維碼的圖片,//兩個for循環是圖片橫列掃描的結果
for (int x = 0; x < QR_WIDTH; x++) {
if (bitMatrix.get(x, y)) {
pixels[y QR_WIDTH + x] = 0xff000000;//黑色
} else {
pixels[y QR_WIDTH + x] = 0xffffffff;//白色
}
}
}
//------------------添加圖片部分------------------//
Bitmap logoBmp = BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher);
Bitmap bitmap = Bitmap.createBitmap(QR_WIDTH, QR_HEIGHT,
Bitmap.Config.ARGB_8888);
//設置像素點
bitmap.setPixels(pixels, 0, QR_WIDTH, 0, 0, QR_WIDTH, QR_HEIGHT);
Canvas canvas = new Canvas(bitmap);
//二維碼
canvas.drawBitmap(bitmap, 0,0, null);
//圖片繪制在二維碼中央,合成二維碼圖片
canvas.drawBitmap(logoBmp, bitmap.getWidth() / 2
- logoBmp.getWidth() / 2, bitmap.getHeight()
/ 2 - logoBmp.getHeight() / 2, null);
//------------------添加logo部分------------------//
code.setImageBitmap(bitmap);
} catch (WriterException e) {
e.printStackTrace();
}
}
}
</pre>