Android 二维码加载到指定背景图的位置

// 从资源加载图片
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'
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容