[ Team LiB ] |
4.5 Drawing TextFor 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. 4.5.1 Attributed stringsAttributes 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. |
[ Team LiB ] |