2009-03-03 50 views
10

我已經想出瞭如何使用NSBezierPath類在我的自定義視圖類的drawRect函數中繪製形狀,但我似乎無法弄清楚如何繪製文本。下面的代碼是我迄今繪製文本(位於的drawRect功能):我猜我可能需要提供一個或的NSRect NSPoint告訴NSText對象在哪裏畫如何使用Objective-C在自定義視圖中繪製文本?

NSText *text = [NSText new]; 
[text setTextColor: [NSColor yellowColor]]; 
[text setText: @"Hello!"]; 

本身,但我在Cocoa文檔中找不到關於如何執行此操作的任何內容。

回答

22

你可以嘗試的東西沿着這些路線:

//note we are using the convenience method, so we don't need to autorelease the object 
NSDictionary *attributes = [NSDictionary dictionaryWithObjectsAndKeys:[NSFont fontWithName:@"Helvetica" size:26], NSFontAttributeName,[NSColor blackColor], NSForegroundColorAttributeName, nil]; 

NSAttributedString * currentText=[[NSAttributedString alloc] initWithString:@"Cat" attributes: attributes]; 

NSSize attrSize = [currentText size]; 
[currentText drawAtPoint:NSMakePoint(yourX, yourY)]; 
+0

完美!非常感謝你的幫助。 – 2009-03-03 03:03:42