Can we add text to a drawable?

我只是一个虾纸丫 提交于 2020-08-06 08:41:12

问题


I want to create a drawable which looks like this.

enter image description here and enter image description here

I know how to create the image background but even after searching, I am unable to find how to give text to that drawable file. Is there any way that the drawable file is exactly same containing the text as well?

I cant use textview because its a tab and I need drawables to set as background resource (thats what I know, please correct me if I am wrong.). So I want a drawable file which I can set as background.

enter image description here


回答1:


Yes you can do that.

See the post -

How to put text in a drawable ?

Basically, you have to extend the class Drawable and set the canvas to draw the text to a drawable.

As you override the draw method, it will take the canvas and draw the text on defined locations.

There are many methods available for Canvas.

As explained in a graphics doc. -

The Canvas class has its own set of drawing methods that you can use, like drawBitmap(...), drawRect(...), drawText(...), and many more. Other classes that you might use also have draw() methods. For example, you'll probably have some Drawable objects that you want to put on the Canvas. Drawable has its own draw() method that takes your Canvas as an argument.

Drawing text will be just like the following -

canvas.drawText("Front Screen Torch", 30, 48, paint);

To get the actual color directly from resources use -

paint.setColor(getResources().getColor(R.color.black));

See Canvas for more.




回答2:


YES you can and Much More With this control over canvas ,I use This alot to To get Full control over the drawable

public static Drawable getTextDrawable(@ColorInt int iColor) {
 Shape shape = new Shape(){

        @Override
        public void draw(Canvas canvas, Paint paint)
        {
            paint.setColor(Color.BLUE);

            paint.setTextSize(100);

            int radii = dpToPx(3);

            canvas.drawText("Hello Canvas", canvas.getWidth() - 150, canvas.getHeight() / 2, paint);

            canvas.drawCircle(canvas.getWidth() - radii * 2, canvas.getHeight() /2 - radii, radii, paint);
        }
    };
    shape.getHeight();

    Drawable drawable = new ShapeDrawable(shape);

    return drawable;
}



回答3:


Can we add text to a drawable ?

No, you can't.

Alternate option for this is to create a drawable with Text.



来源:https://stackoverflow.com/questions/21822526/can-we-add-text-to-a-drawable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!