103 lines
3.1 KiB
Kotlin
103 lines
3.1 KiB
Kotlin
package com.sw.inbound.utils
|
|
|
|
import android.graphics.Bitmap
|
|
import android.graphics.Canvas
|
|
import android.graphics.Color
|
|
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
|
|
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel
|
|
import kotlin.apply
|
|
import kotlin.ranges.until
|
|
import kotlin.text.isEmpty
|
|
|
|
/**
|
|
* 二维码生成工具类
|
|
*/
|
|
object QRCodeUtil {
|
|
|
|
/**
|
|
* 生成二维码(默认大小)
|
|
* @param content 二维码内容
|
|
* @return 生成的二维码Bitmap
|
|
*/
|
|
@JvmOverloads
|
|
fun generateQRCode(content: String, size: Int = 500): Bitmap? {
|
|
return generateQRCode(content, size, Color.BLACK, Color.WHITE)
|
|
}
|
|
|
|
/**
|
|
* 生成二维码(自定义颜色)
|
|
* @param content 二维码内容
|
|
* @param size 二维码边长(像素)
|
|
* @param colorCode 二维码颜色
|
|
* @param backgroundColor 背景颜色
|
|
* @return 生成的二维码Bitmap
|
|
*/
|
|
fun generateQRCode(
|
|
content: String,
|
|
size: Int,
|
|
colorCode: Int,
|
|
backgroundColor: Int
|
|
): Bitmap? {
|
|
if (content.isEmpty()) {
|
|
return null
|
|
}
|
|
|
|
return try {
|
|
val hints = mutableMapOf<EncodeHintType, Any>().apply {
|
|
put(EncodeHintType.CHARACTER_SET, "UTF-8")
|
|
put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H) // 纠错级别
|
|
put(EncodeHintType.MARGIN, 1) // 边距
|
|
}
|
|
|
|
val bitMatrix = QRCodeWriter().encode(
|
|
content,
|
|
BarcodeFormat.QR_CODE,
|
|
size,
|
|
size,
|
|
hints
|
|
)
|
|
|
|
val pixels = IntArray(size * size).apply {
|
|
for (y in 0 until size) {
|
|
for (x in 0 until size) {
|
|
this[y * size + x] = if (bitMatrix.get(x, y)) colorCode else backgroundColor
|
|
}
|
|
}
|
|
}
|
|
|
|
Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888).apply {
|
|
setPixels(pixels, 0, size, 0, 0, size, size)
|
|
}
|
|
|
|
} catch (e: WriterException) {
|
|
e.printStackTrace()
|
|
null
|
|
}
|
|
}
|
|
|
|
/**
|
|
* 生成带Logo的二维码
|
|
* @param content 二维码内容
|
|
* @param size 二维码边长(像素)
|
|
* @param logo Logo Bitmap
|
|
* @return 带Logo的二维码Bitmap
|
|
*/
|
|
fun generateQRCodeWithLogo(content: String, size: Int, logo: Bitmap?): Bitmap? {
|
|
val qrCode = generateQRCode(content, size) ?: return null
|
|
logo ?: return qrCode
|
|
|
|
val logoSize = size / 5 // Logo大小约为二维码的1/5
|
|
val scaledLogo = Bitmap.createScaledBitmap(logo, logoSize, logoSize, false)
|
|
|
|
val offset = (size - logoSize) / 2
|
|
return Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888).apply {
|
|
val canvas = Canvas(this)
|
|
canvas.drawBitmap(qrCode, 0f, 0f, null)
|
|
canvas.drawBitmap(scaledLogo, offset.toFloat(), offset.toFloat(), null)
|
|
}
|
|
}
|
|
} |