swharden / SWHarden.com

The personal website of Scott W Harden
https://swharden.com
MIT License
4 stars 0 forks source link

MeasureString() with Maui.Graphics: Improved Code #7

Open swharden opened 1 year ago

swharden commented 1 year ago

https://swharden.com/blog/2021-10-16-maui-graphics-measurestring/

Thanks Jerry for sending this in:

I noticed that your label was offset some

If you haven't found by now, and if you wanted the text centered in the blue rect, you could change the alignments to center, and use the blue rect width/height:

public void Draw(ICanvas canvas, Microsoft.Maui.Graphics.Font font, float fontSize, RectF rect)
{
      string prompt = "Hello, Maui.Graphics!";
      SizeF strSize = canvas.GetStringSize(prompt, font, fontSize);

      canvas.DrawString
      (
            value: prompt,
            x: rect.X,
            y: rect.Y,
            width: rect.Width,
            height: rect.Height,
            horizontalAlignment: HorizontalAlignment.Center,
            verticalAlignment: VerticalAlignment.Center,
            textFlow: TextFlow.OverflowBounds,
            lineSpacingAdjustment: 0
      );
}