Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to put text in a drawable?

I'm trying to create a drawable on the fly to use as a background for a custom linearlayout. It needs to have hash marks and such (no big deal), but also have numbers labeling what the hash marks are (like a ruler). I know I can just create text elements and put them inside the linearlayout and just have the hash marks in the drawable, but I'm hoping to have them inside the drawable as well, so I don't have to do measurement calculations twice.

like image 481
atraudes Avatar asked Oct 19 '10 20:10

atraudes


People also ask

How do you add text in drawable?

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.

How do I add text to a layer list?

One way to add Texts in your drawable layer-list is by creating a png file of the text and adding it using bitmap.


2 Answers

I've read the book "Professional Android 2 Application Development" (by Reto Meier). Amongst others, it contains an example project where you create a simple compass application where you "draw" text, markers etc.

The brief explanation is that you create a class that extends the android.view.View class and overrides the onDraw(Canvas) method.

All the source code form the book is available for download here: http://www.wrox.com/WileyCDA/WroxTitle/Professional-Android-2-Application-Development.productCd-0470565527,descCd-DOWNLOAD.html. If you download the code and look inside the project named "Chapter 4 Compass", I believe you would find what you're looking for :)

like image 40
Julian Avatar answered Oct 02 '22 18:10

Julian


Here is a brief example of a TextDrawable which works like a normal drawable but lets you specify text as the only constructor variable:

public class TextDrawable extends Drawable {      private final String text;     private final Paint paint;      public TextDrawable(String text) {          this.text = text;          this.paint = new Paint();         paint.setColor(Color.WHITE);         paint.setTextSize(22f);         paint.setAntiAlias(true);         paint.setFakeBoldText(true);         paint.setShadowLayer(6f, 0, 0, Color.BLACK);         paint.setStyle(Paint.Style.FILL);         paint.setTextAlign(Paint.Align.LEFT);     }      @Override     public void draw(Canvas canvas) {         canvas.drawText(text, 0, 0, paint);     }      @Override     public void setAlpha(int alpha) {         paint.setAlpha(alpha);     }      @Override     public void setColorFilter(ColorFilter cf) {         paint.setColorFilter(cf);     }      @Override     public int getOpacity() {         return PixelFormat.TRANSLUCENT;     } } 
like image 111
plowman Avatar answered Oct 02 '22 17:10

plowman