Центрировать все элементы холста - PullRequest
0 голосов
/ 23 февраля 2020

Я разрабатываю приложение, которое добавляет 1 изображение и 2 строки в нижний центр фотографии. Все работает нормально, но когда вторая строка слишком велика, не похоже, что все это в центре.

Вот что у меня сейчас (пример):

current

И вот что мне нужно (образец):

required result

Вот пример кода:

private fun overlay(bmp1: Bitmap, bmp2: Bitmap): Bitmap {
        val bmOverlay = Bitmap.createBitmap(bmp1.width, bmp1.height, bmp1.config)
        val canvas = Canvas(bmOverlay)

        canvas.drawBitmap(bmp1, Matrix(), null)
        energyPositionX = (canvas.width / 2) - (bmp2.width / 2)
        energyPositionY = (canvas.height / 2)
        canvas.drawBitmap(bmp2, energyPositionX.toFloat(), energyPositionY.toFloat(), null)

        return drawTextToBitmap(applicationContext, bmOverlay, 140,"aa", "aaaaa")
    }

    private fun drawTextToBitmap(context: Context, curBitmap: Bitmap, textSize: Int = 78,
                                 text1: String, text2: String): Bitmap {
        val resources = context.resources
        val scale = resources.displayMetrics.density
        var bitmap = curBitmap

        var bitmapConfig = bitmap.config;
        // set default bitmap config if none
        if (bitmapConfig == null) {
            bitmapConfig = Bitmap.Config.ARGB_8888
        }
        // resource bitmaps are imutable,
        // so we need to convert it to mutable one
        bitmap = bitmap.copy(bitmapConfig, true)

        val canvas = Canvas(bitmap)
        // new antialised Paint
        val paint = Paint(Paint.ANTI_ALIAS_FLAG)
        paint.color = Color.WHITE

        // text size in pixels
        paint.textSize = (textSize * scale).roundToInt().toFloat()
        //custom fonts
        //val fontFace = ResourcesCompat.getFont(context, R.font.acrobat)
        //paint.typeface = Typeface.create(fontFace, Typeface.NORMAL)
        // text shadow
        paint.setShadowLayer(1f, 0f, 1f, Color.BLACK)

        // draw text to the Canvas center
        val bounds = Rect()
        //draw the first text
        paint.getTextBounds(text1, 0, text1.length, bounds)
        val x = (bitmap.width - energyPositionX) - bounds.width() - (energyPositionX / 1.3)
        val y = (curBitmap.height / 2) + (curBitmap.height / 4)
        canvas.drawText(text1, x.toFloat(), y.toFloat(), paint)

        //draw the second text
        paint.getTextBounds(text2, 0, text2.length, bounds)
        val x2 = (bitmap.width - energyPositionX) + (energyPositionX / bounds.width() + 50)
        val y2 = (curBitmap.height / 2) + (curBitmap.height / 4)
        canvas.drawText(text2, x2.toFloat(), y2.toFloat(), paint)

        return bitmap
    }

Сначала я центрирую изображение, а затем добавляю текст слева и справа от него. Я знаю, что этот код выглядит не очень хорошо, но я никогда раньше не работал с холстом и изображениями. Надеюсь, вы мне поможете!

...