How to draw text in Xamarin iOS into given coordinates?

JosManuelJosManuel USMember ✭✭
edited June 2017 in Xamarin.iOS

I would like to draw text at a given point (x, y) in the Draw **method of a custom **View.

I have followed this https://developer.xamarin.com/recipes/ios/graphics_and_drawing/core_text/draw_unicode_text_with_coretext/

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!

Tagged:
Sign In or Register to comment.