Sunday, March 20, 2016

iOS: draw text outline with CoreText.

This only works for UILabel, not work with CoreText draw

Make sure to set your UIAttributedString kCTForegroundColorAttributeName with selected color, e.g UIColor redColor

On drawing method:

   CGContextRef context = UIGraphicsGetCurrentContext();  
   CGRect textRect;  
   CTFrameRef frameRef = [self frameRefFromSize:self.bounds.size textRectOutput:&textRect];  
   // Invert everything, because CG works with an inverted coordinate system.  
   CGContextTranslateCTM(context, 0.0, CGRectGetHeight(rect));  
   CGContextScaleCTM(context, 1.0, -1.0);  

   // first draw ouline  
   CGContextSaveGState(context);  
   CGContextSetTextDrawingMode(context, kCGTextFillStroke);  
   CGContextSetLineWidth(context, [self strokeSizeDependentOnStrokePosition]);  
   CGContextSetLineJoin(context, kCGLineJoinRound);  
   [[UIColor blueColor] setStroke];  
   CTFrameDraw(frameRef, context);  
   CGContextRestoreGState(context);  

   // draw text  
   CGContextSaveGState(context);  
   CTFrameDraw(frameRef, context);  
   CGContextRestoreGState(context);  

Result:


For CoreText work, take a look on

Drawing outlined glyphs with CoreText

More advanced topic on CoreText

Befriending Core Text - from Cocoanetics

No comments:

Post a Comment