Search code examples
textxamarin.iosparagraphcore-text

Core Text FrameSetter with monotouch


Using monotouch, I'm try to display a core text element over multiple lines. The example I'm trying to use is from CoreText_Programming p17. One problem I've come across is not being able to find an equivalent for CFMutableAttributedStringRef, so I've tried to subsitute this for NSAttributedString, however the following code displays nothing. Does anyone know of any examples of this type in monotouch or know the reason why the following is not working. Thanks.

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

        CGContext context = UIGraphics.GetCurrentContext ();
        context.TextMatrix = new CGAffineTransform();           
        CGPath path = new CGPath();
        path.AddRect ( this.Bounds );
        // created dictionary so this line does not crash 
        NSAttributedString stringToDraw = new NSAttributedString( "Hello", new NSDictionary() );
        CTFramesetter framesetter = new CTFramesetter(stringToDraw);
        CTFrame frame = framesetter.GetFrame( new NSRange(0,0), path, null );
        frame.Draw( context );
    }

Solution

  • As it happens, I ported most of those samples to MonoTouch when I was writing/testing the MonoTouch.CoreText framework. Then apparently completely forgot to merge them upstream. :-/

    That said, take a look at CoreTextDemo.cs, which ports (nearly line-for-line) most of the samples in the PDF you linked to.

    Based on my CoreTextDemo.cs, you're missing:

    • A proper CGAffineTransform.MakeScale() call: context.TextMatrix = CGAffineTransform.MakeScale(1f, -1f);
    • You're not using NSMutableAttributedString. (CFMutableAttributedStringRef maps to NSMutableAttributedString.)
    • You're not disposing of your framesetter, nor your frame.

    There may be others, but at the time the CoreTextDemo.cs code worked equivalent to the Objective-C code.