Android Development: Drawing Text on a Canvas
In this post, we take a look at a common need when making Android apps: how to put text directly onto a Canvas. Read on to find out how it's done!
Join the DZone community and get the full member experience.
Join For FreeI 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 )
Published at DZone with permission of Kevin Hooke, DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.
Comments