I would like to draw text at a given point (x, y) in the Draw
method of a custom View
.
I have followed this sample from the Xamarin site.
This is the View I created:
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);
}
}
}
The problem is that the DrawText
method only works OK once. The first time you call it the text is drawn, but it doesn't work on successive calls (it draws nothing, or what it draws isn't visible).
What am I doing wrong?
Big thanks!
So there are two basic things that are wrong with your code.
ScaleCTM
and aTranslateCTM
each time you callDrawText
CTLine.Draw
, the "cursor" is moved to the end of that text.So, call
ScaleCTM
to flipped the whole thing so the text gets draw left2right, then callDrawText
and translate to where you want to paint the text and then translate back to where you started so the next time you are at the same point.Example Draw override:
Results in:
Using NSMutableParagraphStyle and NSString.DrawString
I took @SushiHangover's code and modified it to work for me, since their version (1st in his post) had some problems (read notice below):
Keep into account that
FormattedText
andPoint
are custom classes I made to encapsulate the text to be drawn and the point where to draw it. Their properties are as simple as you see :)IMPORTANT: The modifications to @SushiHangover's version are there to
Avoid side effects (if I drew a Rectangle after calling the DrawText method, the coordinates were messed up, for instance). It also had a problem with the x coordinate:
should be
Bit thanks, @SushiHangover. I made it with your really valuable help!