以编程方式将文本放在drawable上的最简单方法

Sla*_*k Y 3 android drawing drawable

我有这个图标: 图标

我打算用它来工作drawable.

Drawable myIcon = getResources().getDrawable( R.drawable.icon );
Run Code Online (Sandbox Code Playgroud)

我需要programmaticaly在其上放一些文本(文件扩展名).

这是我想要的结果: 期望的结果.

我无法制作几个静态图标,因为我可以接收任意文件扩展名

小智 13

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);
    }
Run Code Online (Sandbox Code Playgroud)

使用此方法.将帮助您.

  • 得到“尝试在空对象引用上调用虚拟方法 'android.graphics.Bitmap android.graphics.Bitmap.copy(android.graphics.Bitmap$Config, boolean)'”。复制可以返回“null”。使用前必须检查“bm”是否为空。不知道为什么资源有效 - 仍在研究。 (2认同)