前言:在某些專案裡我們需要生成屬於我們的QRcode給使用著,令他們可以更快更方便的使用我們的程式,此篇就是要介紹如何製作一個自己的QRcode。
dependencies {
...
implementation 'com.google.zxing:core:3.3.0'
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.example.qr.MainActivity">
<ImageView
android:id="@+id/iv"
android:layout_width="169dp"
android:layout_height="147dp"
android:layout_gravity="center" />
</LinearLayout>
public class QRCodeUtil {
@Nullable
public static Bitmap createQRCodeBitmap(
String content, int width, int height,@Nullable String character_set,
@Nullable String error_correction, @Nullable String margin,
@ColorInt int color_black, @ColorInt int color_white){
//此處為防止操作失誤
if(TextUtils.isEmpty(content)){
return null;
}
if(width < 0 || height < 0){
return null;
}
try {
Hashtable<EncodeHintType, String> hints = new Hashtable<>();
if(!TextUtils.isEmpty(character_set)) {
hints.put(EncodeHintType.CHARACTER_SET, character_set); // 字符轉碼設置
}
if(!TextUtils.isEmpty(error_correction)){
hints.put(EncodeHintType.ERROR_CORRECTION, error_correction); // 容錯設置
}
if(!TextUtils.isEmpty(margin)){
hints.put(EncodeHintType.MARGIN, margin); // 空白邊距設置
}
BitMatrix bitMatrix = new QRCodeWriter().encode(content, BarcodeFormat.QR_CODE, width, height, hints);
int[] pixels = new int[width * height];
for(int y = 0; y < height; y++){
for(int x = 0; x < width; x++){
if(bitMatrix.get(x, y)){
pixels[y * width + x] = color_black; // 黑色色塊像素設置
} else {
pixels[y * width + x] = color_white; // 白色色塊像素設置
}
}
}
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;
}
}
public class MainActivity extends AppCompatActivity {
private ImageView mImageView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main)
mImageView = findViewById(R.id.i);
//呼叫工具類並且給予她所需的數值
Bitmap mBitmap = QRCodeUtil.createQRCodeBitmap(
"https://www.google.com.tw/", 400, 480,"UTF-8","H","2", Color.BLACK,Color.WHITE);
mImageView.setImageBitmap(mBitmap);
}
}