Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android canvas.drawText() not showing

Tags:

android

canvas

So, I have this problem where my android text drawn on a canvas on top of a background image is not showing. my code:

@Override
public void draw(Canvas canvas) {
    final float scaleFactorX = getWidth() / WIDTH;
    final float scaleFactorY = getHeight() / HEIGHT;

    if(canvas != null) {
        final int savedState = canvas.save();
        canvas.scale(scaleFactorX, scaleFactorY);

        Paint textPaint = new Paint();
        textPaint.setColor(Color.RED);
        textPaint.setTextSize(20);
        textPaint.setAntiAlias(true);

        canvas.drawBitmap(background, 0, 0, null);
        canvas.drawBitmap(button_start, (canvas.getWidth() - button_start.getScaledWidth(canvas)) / 2, canvas.getHeight() / 4, null);
        canvas.drawText("Test text", 0, 0, textPaint);
        canvas.restoreToCount(savedState);
    }
}

Does anyone have an idea what I am doing wrong?

like image 466
zeno dhaene Avatar asked Jul 12 '15 12:07

zeno dhaene


1 Answers

the y axis of base line is not 0, try this

    Paint textPaint = new Paint(Paint.ANTI_ALIAS_FLAG | Paint.DITHER_FLAG);
    textPaint.setColor(Color.RED);
    textPaint.setTextSize((int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, 20, getResources().getDisplayMetrics()));
    textPaint.setTextAlign(Align.LEFT);
    FontMetrics metric = textPaint.getFontMetrics();
    int textHeight = (int) Math.ceil(metric.descent - metric.ascent);
    int y = (int)(textHeight - metric.descent);
    canvas.drawText("text", 0, y, textPaint);
like image 179
rainash Avatar answered Nov 19 '22 05:11

rainash