Technical Q&A QA1531

Drawing attributed strings that are both filled and stroked

Q:  How can I draw a string that specifies both a fill color and a stroke width?

A: Supply a negative value for NSStrokeWidthAttributeName when you wish to draw a string that is both filled and stroked.

This is because the sign of the value for NSStrokeWidthAttributeName is interpreted as a mode; it indicates whether the attributed string is to be filled, stroked, or both. Specifically, a zero value displays a fill only, while a positive value displays a stroke only. A negative value allows displaying both a fill and stroke.

Figure 1  A zero value for stroke width indicates fill with no stroke.
Figure 2  A positive value makes a stroke with no fill.

The code in Listing 1 demonstrates a custom view rendering an attributed string that's both filled and stroked. The results are in Figure 3.

Listing 1  Render a filled and stroked attributed string.

- (void)drawRect:(NSRect)rect {
    NSString    *string = @"Got Fill?";
    NSMutableDictionary *stringAttributes = [NSMutableDictionary dictionary];
    // Define the font and fill color
    [stringAttributes setObject: [NSFont fontWithName:@"Arial-Black" size:64] forKey: NSFontAttributeName];
    [stringAttributes setObject: [NSColor whiteColor] forKey: NSForegroundColorAttributeName];
    // Supply a negative value for stroke width that is 2% of the font point size in thickness
    [stringAttributes setObject: [NSNumber numberWithFloat: -2.0] forKey: NSStrokeWidthAttributeName];
    [stringAttributes setObject: [NSColor blackColor] forKey: NSStrokeColorAttributeName];
    // Paint the background
    [[NSColor grayColor] set];
    [NSBezierPath fillRect: [self bounds]];
    // Draw the string
    [string drawAtPoint: NSMakePoint(100, 100) withAttributes: stringAttributes];
Figure 3  Supplying a negative value for stroke width creates both a fill and stroke.

See Also

For more information on drawing strings, see the String Programming Guide for Cocoa, the Attributed Strings Programming Guide and Cocoa Drawing Guide: Text.

Document Revision History


Editorial correction.


New document that describes how the value of NSStrokeWidthAttributeName indicates fill, stroke, or both, in attributed strings.