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: Use a negative value for NSStrokeWidthAttributeName when you wish to draw a string that is both filled and stroked.

The sign of the value for NSStrokeWidthAttributeName is used as a mode. This value indicates not just the width of the stroke, but whether the attributed string is to be filled, stroked, or both filled and stroked. A zero width value will show no stroke, only the fill color, while a positive value indicates that it should be only stroked, and a negative value indicates it should be both filled and stroked. The absolute value will be used for the stroke width.

Figure 1: A zero value for stroke width indicates fill with no stroke.

Figure 1, A zero value for stroke width indicates fill with no stroke.

Figure 2: With a positive value for stroke width the string is stroked but not filled.

Figure 2, With a positive value for stroke width the string is stroked but not filled.

The sample code in Listing 1 shows how a custom view might both fill and stroke an attributed string in its drawRect: method. The results are shown in Figure 3.

Listing 1: Specifying that a string is to be drawn with both fill and stroke.

- (void)drawRect:(NSRect)rect {
    NSString    *string = @"Got Fill?";
    NSMutableDictionary *stringAttributes = [NSMutableDictionary dictionary];

    // Set a font and specify a "fill" color
    [stringAttributes setObject: [NSFont fontWithName:@"Arial-Black" size:64] forKey: NSFontAttributeName];
    [stringAttributes setObject: [NSColor whiteColor] forKey: NSForegroundColorAttributeName];

    // Set a negative width so we get both stroke and fill to show
    [stringAttributes setObject: [NSNumber numberWithFloat: -2.0] forKey: NSStrokeWidthAttributeName];
    [stringAttributes setObject: [NSColor blackColor] forKey: NSStrokeColorAttributeName];

    // Now paint the background
    [[NSColor grayColor] set];
    [NSBezierPath fillRect: [self bounds]];

    // And finally draw the string with these attributes
    [string drawAtPoint: NSMakePoint(100, 100) withAttributes: stringAttributes];
}

Figure 3: A negative value for stroke width will produce both fill and stroke.

Figure 3, A negative value for stroke width  will produce both fill and stroke.

See Also

For more information on drawing strings, you may wish to refer the String Programming Guide for Cocoa, the Attributed Strings Programming Guide and Cocoa Drawing Guide: Text.

Document Revision History

DateNotes
2008-03-25First Version

Posted: 2008-03-25


Did this document help you?
Yes: Tell us what works for you.
It’s good, but: Report typos, inaccuracies, and so forth.
It wasn’t helpful: Tell us what would have helped.