2016-12-14 40 views
0

我有这个图标:icon最简单的办法把文本上绘制程序

我打算用它作为工作drawable

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

我需要programmaticaly把一些文本(文件扩展名)。

这是我想要的结果:desired result

我不能让几个静态图标,因为我可以接收任意文件扩展名

+0

这很简单,在'RelativeLayout'内部使用'ImageView'和'TextView'。将TextView的重力设置为布局的中心。 –

+0

这个和其他使用RelativeLayout的答案不适合我,因为我需要接收Drawable。而且我不想将Layout转换为Bitmap/Drawable –

回答

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

使用此method.will帮助你。

+1

谢谢。它与我所需要的相似 –

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

如果您不打印此图片的某个位置,而您只需将其显示在屏幕上,最简单的方法可能是在img的中心打印text

您可以通过使用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> 

这可能是最简单的解决方案,它会在图像的中心,基于尺寸的img对齐文本做到这一点。

相关问题