Android development: drawing text on a Canvas

I have an Android project bubbling away. More details soon πŸ™‚

I’m using a SurfaceView and needed to draw some text on it. The rest of the app is mostly drawing on the SurfaceView Canvas directly, but I need some text too.

I’ve dabbled with some Android development before, and I have to admit getting the layouts to do what you want them too almost seems to suck up the majority of my development time πŸ™ This time round I got sidetracked trying to create a layout that was using a mix of TextView elements and adding my SurfaceView programmatically. This didn’t go too well, didn’t work at all, so I found a few posts like this, and worked out you need to draw directly on the canvas. Something like this does the job:

Paint textPaint = new Paint();
textPaint.setColor(Color.WHITE);
this.canvas.drawText("Hello world!", 20,50, textPaint);

This code is in the middle of a game display loop, but for completeness, to be able to draw to the Canvas first you need:

SurfaceHolder surfaceHolder = this.getHolder();
if (surfaceHolder.getSurface().isValid()) {
    this.canvas = surfaceHolder.lockCanvas();
   ...
}

And then to release the Canvas after you’ve finished drawing:

this.surfaceHolder.unlockCanvasAndPost(this.canvas);

 

Ok, next up, what about custom TTF fonts? Drop the TTF font you want to use in your assets/fonts folder, and then load it up with:

Typeface typeFace = Typeface.createFromAsset(this.context.getAssets(), 
    "fonts/yourfont.ttf");

To use this font with the text snippet above, just call setTypeface() and pass it in:

textPaint.setTypeface(this.typeFace);

Ok, how about specifying a font size that’s proportional to the resolution of the user’s screen? This is an interesting question. To avoid using fixed pixel size fonts and then having them not scale appropriately for different devices with different screen resolutions, Android uses a concept called ‘scale independent pixels’, or SP. This is described in this post here. In short, defines an SP value in /res/values/dimens.xml/dimens.xml like:

<dimen name="scoreFontSize">20sp</dimen>

And then reference and set it like this:

int fontSize = getResources().getDimensionPixelSize(R.dimen.scoreFontSize);
textPaint.setTextSize(fontSize);

Done! (I’ll share more on what I’m working on in a few days πŸ™‚

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.