【问题标题】:How to remove white border/background from Bitmap in Kotlin?如何从 Kotlin 的位图中删除白色边框/背景?
【发布时间】:2021-08-27 07:52:21
【问题描述】:

我有这个功能可以在图像上绘制文本,以便用户可以根据内容分享它

public fun drawTextToBitmap_soul(
context: Context,
gResId: Int,
textSize: Int = 78,
text1: String,
text2: String,
text3: String,
text4: String
): Bitmap {
val resources = context.resources
val scale = resources.displayMetrics.density
var bitmap = BitmapFactory.decodeResource(resources, gResId)

var bitmapConfig = bitmap.config;

if (bitmapConfig == null) {
    bitmapConfig = android.graphics.Bitmap.Config.ARGB_8888
}

bitmap = bitmap.copy(bitmapConfig, true)

val canvas = Canvas(bitmap)

val paint = Paint(Paint.ANTI_ALIAS_FLAG)
paint.color = Color.rgb(255, 255, 255)

paint.textSize = (textSize * scale).roundToInt().toFloat()

val fontFace = ResourcesCompat.getFont(context, R.font.poppins)
paint.typeface = Typeface.create(fontFace, Typeface.NORMAL)

paint.setShadowLayer(1f, 0f, 1f, Color.WHITE)

val bounds = Rect()

paint.getTextBounds(text1, 0, text1.length, bounds)
paint.textAlign = Paint.Align.LEFT
var x = (bitmap.width - bounds.width()) / 20.0
var y = (bitmap.height + bounds.height()) / 4.0
canvas.drawText(text1, x.toFloat(), y.toFloat(), paint)



val paints = TextPaint(Paint.ANTI_ALIAS_FLAG)

paints.color = Color.rgb(255, 255, 255)

paints.textSize = (textSize * scale).roundToInt().toFloat()

paints.setShadowLayer(1f, 0f, 1f, Color.WHITE)


val textWidth = canvas.width - (46 * scale).toInt()


val textLayout = StaticLayout(
    text2, paints, textWidth, Layout.Alignment.ALIGN_NORMAL, 1.0f, 0.0f, false
)

val textLayout2 = StaticLayout(
    text3, paints, textWidth, Layout.Alignment.ALIGN_NORMAL, 1.0f, 0.0f, false
)

val textLayout3 = StaticLayout(
    text4, paints, textWidth, Layout.Alignment.ALIGN_NORMAL, 1.0f, 0.0f, false
)


var textHeight = textLayout.height


x = ((bitmap.width - textWidth) / 2).toFloat().toDouble()
y = ((bitmap.height - textHeight) / 2.5).toFloat().toInt().toDouble()


canvas.save()
canvas.translate(x.toFloat(), y.toFloat())
textLayout.draw(canvas)

textHeight = textLayout2.height
x = ((bitmap.width - textWidth) / 2).toFloat().toDouble()
y = ((bitmap.height - textHeight) / 3.5).toFloat().toInt().toDouble()
canvas.translate(x.toFloat(), y.toFloat())
textLayout2.draw(canvas)
textHeight = textLayout3.height
x = ((bitmap.width - textWidth) / 2).toFloat().toDouble()
y = ((bitmap.height - textHeight) / 5).toFloat().toInt().toDouble()
canvas.translate(x.toFloat(), y.toFloat())
textLayout3.draw(canvas)
canvas.restore()

return bitmap
}

这是结果:

如何去除图片周围的白色边框/背景?

我尝试从 xml 中执行此操作,但它不起作用并且它没有影响任何东西,它来自函数吗?还是我需要在函数中添加任何内容?

【问题讨论】:

    标签: java android kotlin bitmap border


    【解决方案1】:

    白色边框/背景来自对话框本身而不是位图

    dialog!!.window?.setBackgroundDrawableResource(R.drawable.share_mysoul);
    

    所以我不得不在对话框中从这里更改它

    【讨论】: