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.
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]; |
} |
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
Date | Notes |
---|---|
2013-04-29 | Editorial correction. |
2008-03-25 | New document that describes how the value of NSStrokeWidthAttributeName indicates fill, stroke, or both, in attributed strings. |
Copyright © 2013 Apple Inc. All Rights Reserved. Terms of Use | Privacy Policy | Updated: 2013-04-29