我正在尝试使用 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);
虽然高度似乎还可以,但宽度不正确。知道为什么吗?