Search code examples
javaandroidcanvasdrawing2d

Draw text on Canvas with custom Height - Android


I'm drawing text on canvas with this code:

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        canvas.drawColor(Color.WHITE);

        Paint paint = new Paint();
        Rect bounds = new Rect();
        paint.setColor(Color.BLACK);
        paint.setTextSize(50);

        paint.getTextBounds(first, 0, first.length(), bounds);
        canvas.drawText(first, (canvas.getWidth() - bounds.width()) / 2, 50, paint);
    }

Here is result:

First

But I want the text to have bigger height, I want something like this:

Second

I don't want to change the font size, only the height of this text. How can i do this ?


Solution

  • I found solution for this:

    // Closing hardware acceleration
    setLayerType(LAYER_TYPE_SOFTWARE, paint);
    
    paint.getTextBounds(first, 0, first.length(), bounds);
    float posX = (canvas.getWidth() - bounds.width()) / 2; // center
    float posY = ((canvas.getHeight() - bounds.height()) / 2); // center
    
    canvas.scale(1, 10, posX, posY);
    canvas.drawText(first, posX, posY, paint);