Search code examples
iosdrawingcore-graphicscgcontextcore-text

How to get a proper, arbitrarily wide, text stroke?


I am trying to obtain an outer glow effect on some text, similar to that of PhotoShop, such as: enter image description here

I tried using both:

    CGContextSetTextDrawingMode(context, kCGTextStroke);        
    CGContextShowTextAtPoint(context, x, y, "M", 1);

and the CoreText API's to draw attributed strings with a stroke width, (by first drawing the widest, stroke only, all the way to finally only filling the string) with:

    CTLineRef line = CTLineCreateWithAttributedString((CFAttributedStringRef)CFBridgingRetain(stringToDraw));
    CGContextSetAlpha(context, myAlpha);
    CGContextSetTextPosition(context, x, y);
    CTLineDraw(line, context);

Both solutions work fine, until i try to draw them with a stroke width wider than a certain threshold, then weird artifacts starts showing up. These pics show the results from setting the draw mode to kCGTextFillStroke and having a white stroke color with an alpha of 0.5 (and increasing the line width for each screenshot):

enter image description here enter image description here enter image description here

The following pics show instead what actually happens when i draw using attributed strings and have the proper fading effect of the stroke (increasing the strokewidth attribute for each screenshot):

enter image description here enter image description here enter image description here

It looks like a faulty implementation of the stroke algorithm to me, but maybe some of you will know better, does anyone have any idea of how I could get this effect for wider strokes, without having weirdly horned letters?


Solution

  • The spikes seems to be caused by the LineCapStyle. Try different settings