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.
To create an attributed string, initialize the string with text and assigning to it any of the attributes listed in Table 4-2. Any combination of attributes may be assigned to any subset of characters. For example, the first half of an attributed string might use Lucida Grande with 12-point type, while the second half could use 24-point Tengwar.
Once you have set up the attributes of the string satisfactorily, the
string can be drawn in the currently focused view by sending it
either a drawAtPoint
: or
drawInRect
: message. These methods are AppKit
extensions to NSAttributedString
. These methods
work in the same way as the NSString
extensions
discussed previously. You can also determine the size of the bounding
box by sending a size
message to the attributed
string.
Get Cocoa in a Nutshell now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.