Skip to content

Logo is not centered when qrCodeBuilder has margin #195

@Daanfb

Description

@Daanfb

When I add a logo in the QR Code, the logo is shifted to right and bottom. I don't know if i did something wrong with my code or it is a library bug. This is my code:

companion object {
        const val QR_GENERATION_DEBOUNCE_MS = 200L
        const val SIZE_CELL = 30
        const val CELL_PER_ROW_COLUMN = 21 // Version 1 QR code  (Default in QRs)
        const val CELL_ADDED_PER_VERSION =
            4   // Each version adds 4 cells per row/column (Default in QRs)
        const val MARGIN_CELLS = 2
    }

fun generateQRCodeBitmap(value: CustomizeQrState) {

        // 1. Total number of cells (code + margin)
        val numCells = (CELL_PER_ROW_COLUMN + (value.informationDensity - 1) * CELL_ADDED_PER_VERSION)
        val totalCellsWithMargin = numCells + (MARGIN_CELLS * 2)

        // 2. Cell size
        val cellSizePx = (value.targetSizePx.toFloat() / totalCellsWithMargin).toInt().coerceAtLeast(1)

        // 3. Real margin in pixels
        val realMarginPx = MARGIN_CELLS * cellSizePx

        val qrCodeAreaSizePx = cellSizePx * numCells

        val qrCodeBuilder = QRCodeBuilder(shape = value.cellShape).apply {

            withBackgroundColor(value.backgroundColor)

            // Cell colors
            if (value.cellColors.size == 1) {
                withColor(value.cellColors.first())
            } else {
                withGradientColor(
                    startColor = value.cellColors.first(),
                    endColor = value.cellColors.last()
                )
            }

            withInformationDensity(value.informationDensity)
            withSize(cellSizePx)

            withInnerSpacing(value.innerSpacing)
            withMargin(realMarginPx)

            if (value.logoBitmap != null) {

                val maxLogoPx =
                    (qrCodeAreaSizePx * 0.18).toInt()   // Max logo size is 18% of QR code size in order to not affect scanning
                val scaledLogo = scaleBitmap(value.logoBitmap, maxLogoPx)

                val stream = ByteArrayOutputStream()
                scaledLogo.compress(Bitmap.CompressFormat.PNG, 100, stream)
                val logoByteArray = stream.toByteArray()

                withLogo(
                    logo = logoByteArray,
                    width = scaledLogo.width,
                    height = scaledLogo.height
                )

            } else {
                withLogo(
                    logo = null,
                    width = 0,
                    height = 0,
                )
            }
        }


        val qrBitmap = qrCodeBuilder.build(data = data).render().nativeImage() as? Bitmap
}

This is my qr code with a logo:

Image

Metadata

Metadata

Assignees

Labels

bugSomething isn't working

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions