// 从资源加载图片
val largeBitmap = BitmapFactory.decodeResource(resources, R.mipmap.icon_qr_code_bg)
// 190.designDpToPx()设计图二维码的大小
val smallBitmap = CodeUtils.createQRCode(data.referral_code,
190.designDpToPx(),
Color.parseColor("#000000")
)
//position 是二维码在背景图的位置
val position = Point(93.designDpToPx(), 489.designDpToPx())
val scaledCombinedBitmap = combineImagesWithScaling(largeBitmap,smallBitmap,position)
//等比例缩放图片使得图片可以铺满屏幕 不失真
Glide.with(this@MyQrCodeActivity)
.asBitmap() // 确保返回 Bitmap
.load(scaledCombinedBitmap)
.into(object : CustomTarget<Bitmap>() {
override fun onResourceReady(
bitmap: Bitmap,
transition: Transition<in Bitmap>?
) {
// 计算图片高度(保持比例)
val screenWidth = resources.displayMetrics.widthPixels
val aspectRatio = bitmap.height.toFloat() / bitmap.width.toFloat()
val calculatedHeight = (screenWidth * aspectRatio).toInt()
// 设置 ImageView 高度
qrImg.layoutParams = LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
calculatedHeight
)
qrImg.setImageBitmap(bitmap)
}
override fun onLoadCleared(placeholder: Drawable?) {
// 清理资源
}
})
combineImagesWithScaling
fun combineImagesWithScaling(
largeBitmap: Bitmap,
smallBitmap: Bitmap,
position: Point,
scale: Float = 1f
): Bitmap {
val scaledSmall = if (scale != 1f) {
smallBitmap.scale(
(smallBitmap.width * scale).toInt(),
(smallBitmap.height * scale).toInt()
)
} else smallBitmap
val result = createBitmap(largeBitmap.width, largeBitmap.height)
Canvas(result).apply {
drawBitmap(largeBitmap, 0f, 0f, null)
drawBitmap(scaledSmall, position.x.toFloat(), position.y.toFloat(), null)
}
if (scaledSmall != smallBitmap) scaledSmall.recycle()
return result
}
二维码生成器
implementation 'com.github.jenly1314:zxing-lite:3.2.0'