measuring text on scaled canvas

后端 未结 2 747
旧时难觅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条回答
  • 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;
    
    0 讨论(0)
  • 2021-02-09 05:52

    Using Mono for Android I had to use display metrics as shown here:

    public override System.Drawing.SizeF MeasureString(MyFont f, string text)
    {
      Rect r = new Rect();
    
      f.DrawingFont.GetTextBounds(text, 0, text.Length, r);
    
      //Manual scaling using DisplayMetrics due to Android
      //issues for compatibility with older versions
      Android.Util.DisplayMetrics metrics = new Android.Util.DisplayMetrics();
      GetDisplay.GetMetrics(metrics);
    
      return new System.Drawing.SizeF(r.Width(), r.Height() * metrics.Density);
    }
    

    Where f.DrawingFont is an Androdid.Text.TextPaint GetDisplay is:

    private Display GetDisplay()
    {
      return this.GetSystemService(Android.Content.Context.WindowService).JavaCast<Android.Views.IWindowManager>().DefaultDisplay;
    }
    

    And the same method in Java is:

    private Display getDisplay() {
        return ((WindowManager) getContext().getSystemService(
                Context.WINDOW_SERVICE)).getDefaultDisplay();
    }
    
    0 讨论(0)
提交回复
热议问题