Foobar
Foobar

Reputation: 8467

Android/Java - Draw text at the bottom of a bitmap

I am trying to place white text at the bottom of a bitmap. Additionally, I would like to center the text horizontally, but that's optional.

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

I assumed that because I set the y value of the text to bitmap.height - 50, the text would align with the bottom of the bitmap (since textSize is 50f)

However, in reality, the text does not appear at the bottom of the image. How can I fix this?

Here is the corresponding Java code:

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);

Update: I tried and that helped a small amount.

    val metrics = context.resources.displayMetrics

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

Upvotes: 0

Views: 1867

Answers (2)

Rahul Goswami
Rahul Goswami

Reputation: 782

    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);

use this code hope it work as your requirements

Upvotes: 1

Foobar
Foobar

Reputation: 8467

The solution turned out to be really simple. Change

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

It seems like canvas.drawText draws the text with its bottom aligned with the y-coordinate.

Upvotes: 1

Related Questions