Using MonoTouch.CoreText to draw text fragments at specific coordinaates
在UIView上绘制文本行。
现在我需要扩展它来绘制多行文字。基本上很简单。在Draw()方法中,我将多行字符串文本拆分为" \ n"而且我将DrawTextLine()称为任何一行将newLineDY添加到Y. 唯一的问题是任何新的线条绘制都是在前一个X绘制结束后开始的:
AAA BBB CCC
如何避免X位移?可以重置吗?怎么样?我尝试为任何一行应用负DX,但我不知道适用的值。
private const float newLineDY = 40;
public override void Draw()
{
string[] lines = Text.Split("\n".ToCharArray());
float lx = X;
float ly = Y;
foreach (string line in lines)
{
DrawTextLine(line, lx, ly);
//lx -= 100; // negative DX
ly += newLineDY;
}
}
private void DrawTextLine(string text, float x, float y)
{
CGContext gctx = UIGraphics.GetCurrentContext();
gctx.SaveState();
gctx.TranslateCTM(x, y);
//gctx.TextPosition = new CGPoint(x, y);
gctx.ScaleCTM(1, -1);
//gctx.RotateCTM((float)Math.PI * 315 / 180);
gctx.SetFillColor(UIColor.Black.CGColor);
var attributedString = new NSAttributedString(text,
new CTStringAttributes
{
ForegroundColorFromContext = true,
Font = new CTFont("Arial", 24)
});
using (CTLine textLine = new CTLine(attributedString))
{
textLine.Draw(gctx);
}
gctx.RestoreState();
}
Thaks!
答案 0 :(得分:1)
我已经解决了使用referencedString.DrawString(新的CGPoint(x,y)),这是一个更简单的API,如此处所示
所以我的代码变成了:
private const float newLineDY = 40;
public override void Draw()
{
string[] lines = Text.Split("\n".ToCharArray());
float lx = X;
float ly = Y;
foreach (string line in lines)
{
DrawTextLine(line, lx, ly);
ly += newLineDY;
}
}
private void DrawTextLine(string text, float x, float y)
{
NSAttributedString attributedString = new NSAttributedString(
text,
new CTStringAttributes
{
ForegroundColorFromContext = true,
Font = new CTFont("Arial", 24)
});
attributedString.DrawString(new CGPoint(x, y));
}