Drawing Text
For
many applications that use text,
AppKit’s NSTextField or
NSTextView classes are sufficient. However, when
you need to draw text as part of some custom graphics, you may want
to use Cocoa’s string drawing functionality,
provided by AppKit’s extensions to the
NSString and
NSAttributedString.
The Application Kit adds three methods to the
NSString
class—drawAtPoint: withAttributes:,
drawInRect:withAttributes:, and
sizeWithAttributes:—that let you draw
strings in views easily. The string being drawn is placed in the view
to locate the upper-left corner of its bounding box at the point
specified in drawAtPoint:withAttributes:. When
using drawInRect:withAttributes:, the text is
drawn within the rectangle. If the bounding box of the string is
larger than the rectangle, then the string is clipped.
Attributed strings
Attributes are associated with a string by the Foundation class
NSAttributedString. Table 4-2
enumerates these attributes.
|
Attribute identifier |
Type |
Default value |
NSAttachmentAttributeName |
NSTextAttachment |
No default |
NSBackgroundColorAttributeName |
NSColor |
No default |
NSBaselineOffsetAttributeName |
NSNumber |
0.0 |
NSFontAttributeName |
NSFont |
Helvetica 12 points |
NSForegroundColorAttributeName |
NSColor |
Black |
NSKernAttributeName |
NSNumber |
0.0 |
NSLigatureAttributeName |
NSNumber |
1 |
NSLinkAttributeName |
id |
No default |
NSParagraphAttributeName |
NSParagraphStyle |
[NSParagraphStyle defaultParagraphStyle] ... |
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access