将字符串文本转换为位图 [英] Convert String text to Bitmap

查看:24
本文介绍了将字符串文本转换为位图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Is it possible to convert string text that is inside an EditText box into a Bitmap? In other words, is there any way to convert string text into a Bitmap that means the text will display as an image?

下面是我的代码:

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

推荐答案

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

You can create a Bitmap of the appropriate size, create a Canvas for the Bitmap, and then draw your text into it. You can use a Paint object to measure the text so you'll know the size needed for the bitmap. You can do something like this (untested):

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

这篇关于将字符串文本转换为位图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆