CoreGraphics でテキストを描画しようとしています。残念ながら、テキストの幅を返すメソッドはありません。この方法を使用して幅を取得しようとしました:
private float GetTextWidth(CGContext context, string text)
{
float startWidth,
endWidth,
textWidth;
startWidth = context.TextPosition.X;
context.SetTextDrawingMode(CGTextDrawingMode.Invisible);
context.ShowText(text);
endWidth = context.TextPosition.X;
textWidth = endWidth - startWidth;
return textWidth;
}
ただし、複数行のテキストが必要な場合は、フォントも考慮する必要があります。そこで、UILable を使用して、次のようにして値を取得することを考えました。
RectangleF lableRect = new RectangleF((float)rect.X, (float)rect.Y, (float)rect.Width, (float)rect.Height);
UILabel lable = new UILabel(lableRect){
Font = UIFont.FromName(font.Family.ToString(), (float)font.Size),
Text = text,
};
SizeF uiSize = lable.StringSize(lable.Text, lable.Font);
高さは問題ないように見えますが、幅が正しくありません。理由はありますか?