如何覆盖与多行文本图像(文字将在画布的中心) [英] how to overlay image with multiline text(text will be in center of the canvas )
问题描述
我开发的,我用文字覆盖的图像拍摄应用。
I am developing photography apps in that I overlay an image with text.
下面是我的code:
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);
在此code我的覆盖屏幕宽度/ 2和高度/ 2将会显示在顶部的图像文字,但我希望文本是居中对齐。此外,当我写了大量的文字会对齐表格中心的权利。
In this code I overlay the text on screen width/2 and height/2 it will display on top the image but I want the text to be center-aligned. Also when I write a large text it will align form center to right.
有一个看图片,看我怎么想的:
Have a look at the images to see how I want it:
图片背景:
和结果我想:
推荐答案
使用下面的方法来测量文本的高度和宽度。
然后画在画布上的文本时
Use the below methods to measure the height and width of the text. Then when drawing the text on canvas
左=宽度/ 2 - 输出textWidth / 2
结果顶=身高/ 2 - textHeight不同/ 2
但是,如果你需要长文本的多行文本,这将是一个有点棘手。
But if you need a multiple line text for long texts, it will be a bit tricky.
/**
* 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();
}
这篇关于如何覆盖与多行文本图像(文字将在画布的中心)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!