将文本添加到图像中的机器人编程 [英] Add text to image in android programmatically

查看:81
本文介绍了将文本添加到图像中的机器人编程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想打一个应用程序,就像打开android.I的屏幕很动态添加图像tableLayout.I的行只定义XML文件tableLayout和reamining的工作是在java.I已经成功添加图像,但我没有得到任何帮助,这像(我想显示在图像中的文字)和图像的设置文本是一个特定的padding.How办呢?在此先感谢。

I want to make an application just like opening screen of android.I am dynamically adding images to the rows of tableLayout.I have only defined tableLayout in xml file and reamining work is in java.I have added images successfully but i am not getting any help with setting text of that image(I want to display a text under image) and image to be a specific padding.How to do it?Thanks in advance.

推荐答案

使用下面的函数写上的图像文字:

Use the following function to write Text on Images:

private BitmapDrawable writeTextOnDrawable(int drawableId, String text) {

    Bitmap bm = BitmapFactory.decodeResource(getResources(), drawableId)
            .copy(Bitmap.Config.ARGB_8888, true);

    Typeface tf = Typeface.create("Helvetica", Typeface.BOLD);

    Paint paint = new Paint();
    paint.setStyle(Style.FILL);
    paint.setColor(Color.WHITE);
    paint.setTypeface(tf);
    paint.setTextAlign(Align.CENTER);
    paint.setTextSize(convertToPixels(mContext, 11));

    Rect textRect = new Rect();
    paint.getTextBounds(text, 0, text.length(), textRect);

    Canvas canvas = new Canvas(bm);

    //If the text is bigger than the canvas , reduce the font size
    if(textRect.width() >= (canvas.getWidth() - 4))     //the padding on either sides is considered as 4, so as to appropriately fit in the text
        paint.setTextSize(convertToPixels(mContext, 7));        //Scaling needs to be used for different dpi's

    //Calculate the positions
    int xPos = (canvas.getWidth() / 2) - 2;     //-2 is for regulating the x position offset

    //"- ((paint.descent() + paint.ascent()) / 2)" is the distance from the baseline to the center.
    int yPos = (int) ((canvas.getHeight() / 2) - ((paint.descent() + paint.ascent()) / 2)) ;  

    canvas.drawText(text, xPos, yPos, paint);

    return new BitmapDrawable(getResources(), bm);
}



public static int convertToPixels(Context context, int nDP)
{
    final float conversionScale = context.getResources().getDisplayMetrics().density;

    return (int) ((nDP * conversionScale) + 0.5f) ;

}

这篇关于将文本添加到图像中的机器人编程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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