android - 以编程方式将文本添加到android中的图像

标签 android user-interface text imageview tablelayout

我想制作一个应用程序,就像打开 android 屏幕一样。我正在动态地将图像添加到 tableLayout 的行中。我只在 xml 文件中定义了 tableLayout,其余代码在 java 中。我已成功添加图像,但在设置该图像的文本(我想在图像下方显示文本)和将图像设置为特定填充方面没有得到任何帮助。如何操作?提前致谢。

最佳答案

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

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

}

关于android - 以编程方式将文本添加到android中的图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11100428/

相关文章:

java - 后台线程完成后返回 Android Activity

java - 有什么方法可以使标签在 SWT 中可选?

ios - 特殊UIlabel设计

Java 数组打印出奇怪的数字和文本

android - 如何查看默认的android simple_spinner_dropdown_item 样式

java - 只要有非零余数,我的 Bigdecimal 除法就会导致应用程序崩溃?

android - 如果没有 @Provides-annotated 方法,则无法提供 Dagger/MissingBinding Repository

android - 两个 Android Fragment 可以使用相同的 id 吗?

excel - 使用 xlswrite 更改输出中的字体大小和粗体文本

c - 如何比较 ASCII 值