Zeichnen von Text
Auch Text lässt sich direkt auf einem NSView ausgeben. Dafür benötigt man nur zwei Dinge: Den auszugebenden NSString und dessen Position.
Auch Text lässt sich direkt auf einem NSView ausgeben. Dafür benötigt man nur zwei Dinge: Den auszugebenden NSString und dessen Position.
NSString
*helloString = @"Hallo
Welt"; NSPoint textPoint = NSMakePoint(5, 5); [helloString drawAtPoint:textPoint withAttributes:nil]; |
Wie Sie sehen, ist es sehr einfach, aber genau so sieht der Text anschliessend auch aus. Ganz einfach. Sogar die zuvor gesetzte Farbe hat keine Auswirkungen auf den Text. Diese steuern nämlich die Attribute, die für diesen Text aber nicht angegeben wurden.
NSString
*helloString = @"Hallo
Welt"; NSPoint textPoint = NSMakePoint(5, 5); NSMutableDictionary *textAttrib = [[NSMutableDictionary alloc] init]; [textAttrib setObject:[NSFont fontWithName:@"Times" size:40] forKey:NSFontAttributeName]; [textAttrib setObject:[NSColor purpleColor] forKey:NSForegroundColorAttributeName]; [helloString drawAtPoint:textPoint withAttributes:textAttrib]; |

Benötigt man noch komplexeren Text, sollte man zum Typ NSMutableAttributedString greifen. Mit diesem Typ können innerhalb einer Zeichenkette unterschiedliche Schriftarten und Farben verwendet werden, die dann durch eine NSRange festgelegt werden.
NSMutableAttributedString
*attribString = [[NSMutableAttributedString alloc] initWithString:@"Cocoa lernen Schritt für Schritt"]; [attribString addAttribute:NSFontAttributeName value:[NSFont fontWithName:@"Arial" size:20] range:NSMakeRange(0,6)]; [attribString addAttribute:NSForegroundColorAttributeName value:[NSColor redColor] range:NSMakeRange(0,6)]; [attribString addAttribute:NSFontAttributeName value:[NSFont fontWithName:@"Times" size:30] range:NSMakeRange(6,7)]; [attribString addAttribute:NSForegroundColorAttributeName value:[NSColor blueColor] range:NSMakeRange(6,7)]; [attribString addAttribute:NSFontAttributeName value:[NSFont fontWithName:@"Arial" size:18] range:NSMakeRange(13,19)]; [attribString addAttribute:NSUnderlineStyleAttributeName value:[NSNumber numberWithInt:2] range:NSMakeRange(13,19)]; [attribString addAttribute:NSForegroundColorAttributeName value:[NSColor blackColor] range:NSMakeRange(13,19)]; NSPoint textPoint2 = NSMakePoint(22, 150); [attribString drawAtPoint:textPoint2]; |
