Draw Unicode Text with CoreText

PDF for offline use
Sample Code:
Related SDKs:

Let us know how you feel about this

Translation Quality


0/250

This recipe shows how to draw text using Core Text.

Recipe

  1. In a UIView subclass override Draw and set graphics context state.
var gctx = UIGraphics.GetCurrentContext ();
  gctx.TranslateCTM (10, 0.5f * Bounds.Height);
  gctx.ScaleCTM (1, -1);
  gctx.RotateCTM ((float)Math.PI * 315 / 180);
  gctx.SetFillColor (UIColor.Green.CGColor);
  1. Create a Unicode text string.
string someText = "你好世界";
  1. Create an NSAttributedString.
var attributedString = new NSAttributedString (someText,
       new CTStringAttributes{
          ForegroundColorFromContext =  true,
          Font = new CTFont ("Arial", 24)
});
  1. Pass the NSAttributedString to a CTLine and draw the CTLine.
using (var textLine = new CTLine (attributedString)) {
       textLine.Draw (gctx);
}

Additional Information

You can draw text using the Core Text framework by creating an NSAttributedString instance; passing it to a CTLine instance and calling Draw on the CTLine. Otherwise, normal Core Graphics techniques such as obtaining a graphics context and manipulating the current transformation matrix apply. This example draws text of a given font and color and rotates it as shown above.

Xamarin Workbook

If it's not already installed, install the Xamarin Workbooks app first. The workbook file should download automatically, but if it doesn't, just click to start the workbook download manually.