因此,您的代码有两个基本问题。
- 你正在执行一个
ScaleCTM
and a TranslateCTM
每次你打电话DrawText
- 当你
CTLine.Draw
,“光标”移动到该文本的末尾。
所以,打电话ScaleCTM
翻转整个内容,以便文本从左到右绘制,然后调用DrawText
并翻译到您想要绘制文本的位置,然后翻译回来到您开始的地方,以便下次您在同一点。
绘制覆盖示例:
public override void Draw(CGRect rect)
{
var context = UIGraphics.GetCurrentContext();
context.ScaleCTM(1, -1); // you flipped the context, now you must use negative Y values to draw "into" the view
var textHeight = new CTFont("Arial", 16).CapHeightMetric; // lets use the actaul height of the font captials.
DrawText(context, "Hello", textHeight, 0, 0);
DrawText(context, "How are you?", textHeight, 0, 20);
DrawText(context, "Sincerely,", textHeight, 0, 40);
DrawText(context, "StackOverflow,", textHeight, 0, 60);
}
void DrawText(CGContext context, string text, nfloat textHeight, nfloat x, nfloat y)
{
context.TranslateCTM(-x, -(y + textHeight));
context.SetFillColor(UIColor.Red.CGColor);
var attributedString = new NSAttributedString(text,
new CTStringAttributes
{
ForegroundColorFromContext = true,
Font = new CTFont("Arial", 16)
});
CGRect sizeOfText;
using (var textLine = new CTLine(attributedString))
{
textLine.Draw(context);
sizeOfText = textLine.GetBounds(CTLineBoundsOptions.UseOpticalBounds);
}
// Reset the origin back to where is was
context.TranslateCTM(x - sizeOfText.Width, y + sizeOfText.Height);
}
结果是:
使用 NSMutableParagraphStyle 和 NSString.DrawString
var context = UIGraphics.GetCurrentContext();
CGRect textRect = new CGRect(0.0f, 0.0f, 200.0f, 100.0f);
{
var textContent = "Hello\nHow are you?\nSincerely,\nStackOverflow";
UIColor.Red.SetFill();
var textStyle = new NSMutableParagraphStyle ();
textStyle.Alignment = UITextAlignment.Left;
var textFontAttributes = new UIStringAttributes () {Font = UIFont.FromName("ArialMT", 16.0f), ForegroundColor = UIColor.Red, ParagraphStyle = textStyle};
var textTextHeight = new NSString(textContent).GetBoundingRect(new CGSize(textRect.Width, nfloat.MaxValue), NSStringDrawingOptions.UsesLineFragmentOrigin, textFontAttributes, null).Height;
context.SaveState();
context.ClipToRect(textRect);
new NSString(textContent).DrawString(new CGRect(textRect.GetMinX(), textRect.GetMinY() + (textRect.Height - textTextHeight) / 2.0f, textRect.Width, textTextHeight), UIFont.FromName("ArialMT", 16.0f), UILineBreakMode.WordWrap, UITextAlignment.Left);
context.RestoreState();
}