How to set a drawText in a SurfaceView
-
27-05-2021 - |
Question
Well I've createad a SurfaceView that displays a bitmap, without problems. But I want to display a Text in the bottom of the screen, I think it can be called the canvas.
I tried to draw the text the same way than i did with the bitmap, but without success. I get de force close error.
I've got something like this:
public void run() {
while (isRunning) {
if (!ourHolder.getSurface().isValid())
continue;
Canvas canvas = ourHolder.lockCanvas();
canvas.drawColor(Color.WHITE);
canvas.drawText(score, 200, 100, null);
canvas.drawBitmap(enemy1, enemy1X, enemy1Y, null); // DRAW FIRST
// ENEMY
ourHolder.unlockCanvasAndPost(canvas);
I already tried to set up a new Paint too, instead of using the "null", but it didn't worked as well :/
Can you please tell how it must be done, or why it isn't working. Im new to Android Programming...
Thanks ;)
Solution
Strange. Сode looks clear. The picture does not cover the text?
Yet assign a text paint and set the color. Try this for tests:
Canvas canvas = null;
try {
canvas = ourHolder.lockCanvas();
synchronized (ourHolder) {
canvas.drawColor(Color.WHITE);
canvas.drawBitmap(enemy1, enemy1X, enemy1Y, null);
Paint paint = new Paint();
paint.setColor(Color.RED);
canvas.drawText("XXXX", 200, 100, paint);
}
} catch (Exception e) {
Log.e(TAG, "run() lockCanvas()", e);
} finally {
if (canvas != null) {
ourHolder.unlockCanvasAndPost(canvas);
}
}
ADD
The SurfaceView dimension is greater than 200х100? Try canvas.drawText("XXXX", 20, 20, paint);