问题
I want to create a drawable which looks like this.
and
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.
回答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