measuring text on scaled canvas

后端 未结 2 746
旧时难觅i
旧时难觅i 2021-02-09 04:51

I\'ve been struggling with text measuring and scaled canvases.

When the canvas is unscaled, getTextBounds and measureText deliver accurate results. However, when the ca

2条回答
  •  梦毁少年i
    2021-02-09 05:37

    Ok, just found out how to circumvent the issue.

    The problem is that the Paint does not know about the Canvas scaling. Therefore measureText and getTextBounds deliver the unscaled result. But since the font size does not scale linearly (however, the drawn rect does ), you have to make up for that effect manually.

    So the solution would be:

    // paint the text as usual
    Paint paint = new Paint();
    paint.setTypeface(font);
    paint.setTextSize(fontSize);
    canvas.drawText(text, x, y, paint);
    
    
    // measure the text using scaled font size and correct the scaled value afterwards
    Paint paint = new Paint();
    paint.setTypeface(font);
    paint.setTextSize(fontSize * scaling);
    float w = paint.measureText(text) / scaling;
    

提交回复
热议问题