1

我正在尝试使用 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);

虽然高度似乎还可以,但宽度不正确。知道为什么吗?

4

1 回答 1

5

试试NSString。它具有各种重载,例如:

SizeF size = new NSString (s).StringSize (font, UIScreen.MainScreen.Bounds.Width, UILineBreakMode.TailTruncation);

如果您想要 aUILabel适合包含的字符串,您也可以调用UILabel.SizeToFit(). 或者,如果您想知道 UILabel 中字符串的大小,请使用UILabel.StringSize()

于 2012-06-28T20:09:36.493 回答