Android / Java-在位图的底部绘制文本

时间:2018-08-24 05:23:17

标签: java android bitmap kotlin android-bitmap

我正在尝试在位图的底部放置白色文本。另外,我想将文本水平居中,但这是可选的。

val canvas = Canvas(bitmap)
val paint = Paint()
paint.color = Color.WHITE
paint.textSize = 50f
canvas.drawText("Meme Text", 30f, bitmap.height - 50f, paint)

我假设因为将文本的y值设置为bitmap.height - 50,所以文本将与位图的底部对齐(因为textSize50f

但是,实际上,文本不会出现在图像的底部。我该如何解决?

以下是相应的Java代码:

Bitmap bitmap = ... // Load your bitmap here
Canvas canvas = new Canvas(bitmap);
Paint paint = new Paint(); 
paint.setColor(Color.BLACK); 
paint.setTextSize(10); 
canvas.drawText("Some Text here", x, y, paint);

更新:我尝试了一下,但有帮助。

    val metrics = context.resources.displayMetrics

    canvas.drawText("Meme Text", 30f,canvas.height
            - paint.textSize/metrics.density, paint)

2 个答案:

答案 0 :(得分:0)

    Canvas canvas = new Canvas(bitmap);
// new antialised Paint
Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
// text color - #3D3D3D
paint.setColor(Color.rgb(110,110, 110));
// text size in pixels
paint.setTextSize((int) (12 * scale));
// text shadow
paint.setShadowLayer(1f, 0f, 1f, Color.DKGRAY);

// draw text to the Canvas center
Rect bounds = new Rect();
paint.getTextBounds(mText, 0, mText.length(), bounds);
int x = (bitmap.getWidth() - bounds.width())/6;
int y = (bitmap.getHeight() + bounds.height())/5;

canvas.drawText(mText, x * scale, y * scale, paint);

使用此代码,希望它能按您的要求工作

答案 1 :(得分:-1)

该解决方案非常简单。更改

canvas.drawText("Meme Text", 30f, bitmap.height - 50f, paint) canvas.drawText("Meme Text", 30f, bitmap.height, paint)

似乎canvas.drawText绘制的文本的底部与y坐标对齐。