以编程方式将文本放置在可绘制对象上的最简单方法

5

我有这个图标:icon

我将按照 drawable 的方式使用它。

Drawable myIcon = getResources().getDrawable( R.drawable.icon );

我需要以编程方式在文件扩展名上放置一些文本。

这是我的期望结果:desired result

我无法创建多个静态图标,因为我可以接收任意文件扩展名。


很简单,只需在RelativeLayout中放置一个ImageView和TextView。将TextView的gravity设置为Layout的中心即可。 - Ravi
这个和其他使用RelativeLayout的答案对我来说不太合适,因为我需要接收Drawable。而且我不想将布局转换为位图/Drawable。 - Slavik Y
3个回答

18
public BitmapDrawable writeOnDrawable(int drawableId, String text){

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

        Paint paint = new Paint(); 
        paint.setStyle(Style.FILL);  
        paint.setColor(Color.BLACK); 
        paint.setTextSize(20); 

        Canvas canvas = new Canvas(bm);
        canvas.drawText(text, 0, bm.getHeight()/2, paint);

        return new BitmapDrawable(bm);
    }

使用此方法将有所帮助。


1
好的解决方案 - Elias Fazel
不知何故,这会大幅减小可绘制对象的大小。我已经尝试将图标放置在drawable-nodpi等文件夹中,但问题仍然存在 :( - Mohsin Falak
修复代码如下: return new BitmapDrawable(context.getResources(), bm); - Mohsin Falak
1
出现了“尝试在空对象引用上调用虚拟方法'android.graphics.Bitmap android.graphics.Bitmap.copy(android.graphics.Bitmap$Config, boolean)'。”的错误。copy可能会返回“null”。在使用之前必须检查“bm”是否为空。不确定为什么,因为资源是有效的-仍在研究中。 - G. Steve

2
            <RelativeLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content">


                <ImageView
                    android:id="@+id/folder"
                    android:src="@drawable/image_name"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content" />


                 <TextView

                    android:textColor="@color/green"
                    android:textStyle="bold"
                    android:id="@+id/text"
                    android:text="10"
                    android:layout_centerInParent="true"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content" />
            </RelativeLayout>

0
如果您不打算在某个地方打印此图像,而只需在屏幕上显示它,那么最简单的方法可能是将text打印在img的中心位置。
您可以通过使用RelativeLayout来实现。
<RelativeLayout> // Only works inside a RelativeLayout
  <ImageView
    android:id="@+id/myImage"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:src="@drawable/myImageSouce" />

  <TextView
    android:id="@+id/myImageText"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignLeft="@+id/myImage"
    android:layout_alignTop="@+id/myImage"
    android:layout_alignRight="@+id/myImage"
    android:layout_alignBottom="@+id/myImage"
    android:layout_margin="1dp"
    android:gravity="center"
    android:text="Hello"
    android:textColor="#000000" />
 </RelativeLayout>

这可能是最简单的解决方案,它将根据图像大小将文本居中对齐。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接