且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

字符串文本转换为位图

更新时间:2023-02-03 08:20:22

您可以创建适当大小的位图,创建一个帆布为位图,然后绘制文本到它。您可以使用画图对象要测量的文本,让您知道所需的位图的大小。你可以这样做(未经测试):

 公共位图textAsBitmap(字符串文本,浮TEXTSIZE,诠释文字颜色){
    涂料粉刷=新的油漆();
    paint.setTextSize(TEXTSIZE);
    paint.setColor(文字颜色);
    paint.setTextAlign(Paint.Align.LEFT);
    浮基线= -paint.ascent(); //上升()是负
    INT宽度=(INT)(paint.measureText(文字)+ 0.5F); // 回合
    INT身高=(INT)(基线+ paint.descent()+ 0.5F);
    位图图像= Bitmap.createBitmap(宽度,高度,Bitmap.Config.ARGB_8888);
    帆布油画=新的Canvas(形象);
    canvas.drawText(文字,0,基线,油漆);
    返回形象;
}
 

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?

Below is my Code:

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

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