【发布时间】:2019-07-26 02:44:00
【问题描述】:
我想在自定义 View 的 Draw 方法中的给定点 (x, y) 处绘制文本。
我已从 Xamarin 网站关注 this sample。
这是我创建的视图:
public class MyView : UIView
{
public override void Draw(CGRect rect)
{
using (var context = UIGraphics.GetCurrentContext())
{
DrawText(context, "hello", 20, new CGPoint(0, 0));
DrawText(context, "how are you", 20, new CGPoint(0, 40));
}
}
private void DrawText(CGContext context, string text, int textHeight, CGPoint point)
{
var x = point.X;
var y = point.Y + textHeight;
context.TranslateCTM(x, y);
context.ScaleCTM(1, -1);
context.SetFillColor(UIColor.Red.CGColor);
var attributedString = new NSAttributedString(text,
new CTStringAttributes
{
ForegroundColorFromContext = true,
Font = new CTFont("Arial", 16)
});
using (var textLine = new CTLine(attributedString))
{
textLine.Draw(context);
}
}
}
问题在于DrawText 方法只能正常工作一次。第一次调用它时,会绘制文本,但它在连续调用时不起作用(它什么也不绘制,或者它绘制的内容不可见)。
我做错了什么?
【问题讨论】:
-
嗯 - 你需要类似
setNeedsLayout或类似的东西吗?只是一个疯狂的猜测! -
在iOS中,基本上,只再次使用drawRect例程,当
setNeedsLayout.... -
应该需要调用SetNeedsLayout。我只想在相同的上下文中绘制另一个文本。
标签: c# ios .net xamarin xamarin.ios