I am trying to draw some text with CoreGraphics. Unfortunately there is no method which returns the width of the text. I tried getting the width using this method:
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;
}
but if I want a multiline text I also need to take the font into consideration.
So I thought about using a UILable and get the values from it doing the following:
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);
Although the height seems to be ok, the width is not correct. Any idea why?
Try
NSString. It has various overloads like:If you want a
UILabelto fit the contained string you can also just callUILabel.SizeToFit(). Or if you want to know the size of a string in a UILabel, useUILabel.StringSize()