【问题标题】:Add text to image in android programmatically以编程方式将文本添加到android中的图像
【发布时间】:2012-06-19 11:58:19
【问题描述】:

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

【问题讨论】:

  • 我建议你使用GridView。

标签: android user-interface text imageview tablelayout


【解决方案1】:

使用以下函数在图像上写入文本:

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

}

【讨论】:

  • 如何在位图上添加粗体文本?有选择吗?请指导我。
  • 你的方法对我有用,除了文本大小。我必须将文本大小(x5)设置为在我的可绘制图标中可读。这可能是由于我的设备的转换比例。谢谢!
  • 这里的 mContext 是什么?
  • @Arun George 我在我的项目中使用了上面的代码。有效。但一个小问题是位图图像的大小非常大,使用此功能后存储在 SD 卡上,高达 4MB。但我需要最多 1 MB 或更少。请你指导我。并感谢上面的代码
  • here 是此代码的 KOTLIN 版本
【解决方案2】:

您可以改为使用 RelativeLayout 将 TextView 叠加到 ImageView :)

【讨论】:

  • 是的。我现在已经完成了。我设法在表格行中添加 FrameLayout 并且效果很好。谢谢大家。
【解决方案3】:

这是 Kotlin 版本 Arun 的 solution

import org.jetbrains.anko.dip

fun Context.writeTextOnDrawable(drawableId: Int, text: String) =
        DrawableUtil.writeTextOnDrawableInternal(this, drawableId, text, 25, -2, 0)

object DrawableUtil {

    fun writeTextOnDrawableInternal(context: Context, drawableId: Int, text: String,
            textSizeDp: Int, horizontalOffset: Int, verticalOffset: Int): BitmapDrawable {

        val bm = BitmapFactory.decodeResource(context.resources, drawableId)
                .copy(Bitmap.Config.ARGB_8888, true)

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

        val paint = Paint()
        paint.style = Paint.Style.FILL
        paint.color = Color.WHITE
        paint.typeface = tf
        paint.textAlign = Paint.Align.LEFT
        paint.textSize = context.dip(textSizeDp).toFloat()

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

        val canvas = 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.textSize = context.dip(12).toFloat()

        //Calculate the positions
        val xPos = canvas.width.toFloat()/2 + horizontalOffset  

        //"- ((paint.descent() + paint.ascent()) / 2)" is the distance from the baseline to the center.
        val yPos = (canvas.height / 2 - (paint.descent() + paint.ascent()) / 2) + verticalOffset

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

        return BitmapDrawable(context.resources, bm)
    }
}

【讨论】:

    【解决方案4】:

    我成功实现了在图像上添加文本的问题。看看下面的代码。首先将一个视图作为该布局中的相对布局在该 EditText 和该按钮之后获取 ImageView。给每个人一个id。下面写一个loadBitmapFromView函数。

    public Bitmap loadBitmapFromView(View v) {
            Bitmap b = Bitmap.createBitmap(v.getWidth(), v.getHeight(), Config.ARGB_8888);
            Canvas c = new Canvas(b);
            v.layout(v.getLeft(), v.getTop(), v.getRight(), v.getBottom());
            v.draw(c);
            return b;
        }
    

    点击按钮。

                   Bitmap bitmap = loadBitmapFromView(relativeLayout);
                    File dir = new File(Environment.getExternalStorageDirectory().getAbsolutePath(),         "folderName");
                    if (!dir.exists())
                        dir.mkdirs();
    
                    File file = new File(dir, "capture.jpg");
                    try {
                        FileOutputStream fos = new FileOutputStream(file);
                        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
                        imageView.setImageBitmap(bitmap);    
                    } catch (Exception e) {
                        Log.e("ExpressionEditImageActivity", "Error, " + e);
                    }
    

    享受...

    更多参考,请参考以下截图:

    【讨论】:

    • 感谢这个不错的解决方案。你能帮忙解决一下代码行`Bitmap bitmap = loadBitmapFromView(relativeLayout)` 我无法得到referencerelativeLayout ...如果我给IDRelativeLayout 它不接受它。你能解释一下吗。谢谢
    • 传递你的父视图,在我的例子中,它是相对布局。
    • 好吧..我无法想象这一点。你能用一些示例代码解释一下吗?谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-03-20
    • 2010-12-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多