Using MonoTouch.CoreText to draw text fragments at

2019-08-05 17:33发布

问题:

I am trying to get a grasp of CoreText, working from the example app at http://docs.xamarin.com/recipes/ios/graphics_and_drawing/core_text/draw_unicode_text_with_coretext/

As a test I want to write to write 'N', 'E', 'S' and 'W' on the view in the respective positions. But only the first one (the 'N') gets drawn.

Here's my version of TextDrawingView.cs:

using System;
using System.Drawing;
using MonoTouch.UIKit;
using MonoTouch.Foundation;
using MonoTouch.CoreText;
using MonoTouch.CoreGraphics;

namespace CoreTextDrawing
{
    public class TextDrawingView : UIView
    {
        public TextDrawingView ()
        {
        }

        //based upon docs.xamarin.com/recipes/ios/graphics_and_drawing/\
        //    core_text/draw_unicode_text_with_coretext/

        public override void Draw (RectangleF rect)
        {
            base.Draw (rect);

            var gctx = UIGraphics.GetCurrentContext ();
            gctx.SetFillColor (UIColor.Green.CGColor);

            DrawText ("N", Bounds.Width / 2, Bounds.Height / 4, gctx);
            DrawText ("W", Bounds.Width / 4, Bounds.Height / 2, gctx);
            DrawText ("E", Bounds.Width / 4 * 3, Bounds.Height / 2, gctx);
            DrawText ("S", Bounds.Width / 2, Bounds.Height / 4 * 3, gctx);
        }

        private void DrawText (string t, float x, float y, CGContext gctx)
        {
            gctx.TranslateCTM (x, y);
            gctx.ScaleCTM (1, -1);
            var attributedString = new NSAttributedString (t,
                                       new CTStringAttributes {
                    ForegroundColorFromContext = true,
                    Font = new CTFont ("Arial", 24)
                }); 

            using (var textLine = new CTLine (attributedString)) { 
                textLine.Draw (gctx);
            }
        }
    }
}

I have no idea why only the 'N' gets drawn. Each of the 4 DrawText invocations work fine if they are the only invocation.

I seem to lack some basic understanding.

Basically I want to draw some letters at specific coordinates on the screen, but failed to understand how to achieve this.

Any help, any one?

TIA,

Guido

回答1:

You need to save and restore the context state in the beginning and end of your DrawText method.

gctx.SaveState(); 
...
Transformations
DrawText
...
gctx.RestoreState();