gpt4 book ai didi

android - 将字符串文本转换为位图

转载 作者:IT老高 更新时间:2023-10-28 23:26:30 28 4
gpt4 key购买 nike

是否可以将 EditText 框中的字符串文本转换为位图?换句话说,有没有办法将字符串文本转换为位图,这意味着文本将显示为图像?

以下是我的代码:

class TextToImage extends Activity {

protected void onCreate(Bundle savedInstanceState) {
//create String object to be converted to image
String sampleText = "SAMPLE TEXT";
String fileName = "Image";

//create a File Object
File newFile = new File("./" + fileName + ".jpeg");

//create the font you wish to use
Font font = new Font("Tahoma", Font.PLAIN, 11);

//create the FontRenderContext object which helps us to measure the text
FontRenderContext frc = new FontRenderContext(null, true, true);
}
}

最佳答案

您可以创建一个适当大小的位图,为该位图创建一个 Canvas ,然后在其中绘制您的文本。您可以使用 Paint 对象来测量文本,以便了解位图所需的大小。你可以这样做(未经测试):

public Bitmap textAsBitmap(String text, float textSize, int textColor) {
Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
paint.setTextSize(textSize);
paint.setColor(textColor);
paint.setTextAlign(Paint.Align.LEFT);
float baseline = -paint.ascent(); // ascent() is negative
int width = (int) (paint.measureText(text) + 0.5f); // round
int height = (int) (baseline + paint.descent() + 0.5f);
Bitmap image = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(image);
canvas.drawText(text, 0, baseline, paint);
return image;
}

关于android - 将字符串文本转换为位图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8799290/

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