gpt4 book ai didi

java - 如何用多行文本覆盖图像(文本将位于 Canvas 的中心)

转载 作者:行者123 更新时间:2023-11-29 05:52:47 33 4
gpt4 key购买 nike

我正在开发摄影应用程序,因为我会在图像上叠加文字。

这是我的代码:

Bitmap mBitmap = BitmapFactory.decodeResource(getResources(),
R.drawable.themes11);
// create a mutable bitmap with the same size as the background image's size
bmOverlay = Bitmap.createBitmap(mBitmap.getWidth(),
mBitmap.getHeight(), Bitmap.Config.ARGB_4444);
// create a canvas on which to draw
Canvas canvas = new Canvas(bmOverlay);
TextPaint paint = new TextPaint();
paint.setColor(Color.RED);

paint.setTextSize(40);
paint.setFlags(Paint.ANTI_ALIAS_FLAG);
// if the background image is defined in main.xml, omit this line
canvas.drawBitmap(mBitmap, 0, 0, null);

// draw the text and the point
canvas.drawPoint(50, 100, paint);
// canvas.drawText(InstaTextActivity.CurrentWord, 300, 200, paint);
StaticLayout layout = new StaticLayout(InstaTextActivity.CurrentWord,
paint, display.getHeight(),
android.text.Layout.Alignment.ALIGN_NORMAL, (float) 1.0,
(float) 0.0, true);

canvas.translate(width / 5, height / 5);
layout.draw(canvas);
imageview_img.setImageBitmap(bmOverlay);

在此代码中,我将文本覆盖在屏幕宽度/2 和高度/2 上,它将显示在图像顶部,但我希望文本居中对齐。此外,当我写一个大文本时,它会将表格中心向右对齐。

看看图片,了解我想要的效果:

图片背景:

Backgorund Image

我想要的结果:

result

最佳答案

使用以下方法测量文本的高度和宽度。然后在canvas上绘制文字的时候

left = width/2 - textWidth/2
top = height/2 - textHeight/2

但是如果长文本需要多行文本,那就有点棘手了。

/**
* Method to get the height of the paint
*
* @param brush The TextPaint used to paint the text
* @param text The text which needs to be measured
* @return height of the text
*/
public static int measureTextHeight(Paint brush, String text) {
Rect result = new Rect();
// Measure the text rectangle to get the height
brush.getTextBounds(text, 0, text.length(), result);
return result.height();
}
/**
* Method to get the width of the paint
*
* @param brush The TextPaint used to paint the text
* @param text The text which needs to be measured
* @return width of the text
*/
public static int measureTextWidth(Paint brush, String text) {
Rect result = new Rect();
// Measure the text rectangle to get the height
brush.getTextBounds(text, 0, text.length(), result);
return result.width();
}

关于java - 如何用多行文本覆盖图像(文本将位于 Canvas 的中心),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13285510/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com