Using MonoTouch.CoreText to draw text fragments at specific coordinaates

╄→尐↘猪︶ㄣ 提交于 2019-12-24 17:16:51

问题


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();


来源:https://stackoverflow.com/questions/21309082/using-monotouch-coretext-to-draw-text-fragments-at-specific-coordinaates

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!