我正在制作一个应用程序,这是一个独立的菜单项,代码的基础是我在网站上找到的示例代码。示例代码使用一个数字作为菜单图标,但我希望将其更改为图像。
我希望它像其他应用程序一样,当它不被点击时显示icon.png,当被点击时显示icon-active.png。
当前代码是这样的:
- (void)drawRect:(NSRect)rect {
// Draw background if appropriate.
if (clicked) {
[[NSColor selectedMenuItemColor] set];
NSRectFill(rect);
}
// Draw some text, just to show how it's done.
NSString *text = @"3"; // whatever you want
NSColor *textColor = [NSColor controlTextColor];
if (clicked) {
textColor = [NSColor selectedMenuItemTextColor];
}
NSFont *msgFont = [NSFont menuBarFontOfSize:15.0];
NSMutableParagraphStyle *paraStyle = [[NSMutableParagraphStyle alloc] init];
[paraStyle setParagraphStyle:[NSParagraphStyle defaultParagraphStyle]];
[paraStyle setAlignment:NSCenterTextAlignment];
[paraStyle setLineBreakMode:NSLineBreakByTruncatingTail];
NSMutableDictionary *msgAttrs = [NSMutableDictionary dictionaryWithObjectsAndKeys:
msgFont, NSFontAttributeName,
textColor, NSForegroundColorAttributeName,
paraStyle, NSParagraphStyleAttributeName,
nil];
[paraStyle release];
NSSize msgSize = [text sizeWithAttributes:msgAttrs];
NSRect msgRect = NSMakeRect(0, 0, msgSize.width, msgSize.height);
msgRect.origin.x = ([self frame].size.width - msgSize.width) / 2.0;
msgRect.origin.y = ([self frame].size.height - msgSize.height) / 2.0;
[text drawInRect:msgRect withAttributes:msgAttrs];
}此外,我发现了一篇描述如何做到这一点的方法的帖子,但它对我不起作用。它的网址是:http://mattgemmell.com/2008/03/04/using-maattachedwindow-with-an-nsstatusitem/comment-page-1#comment-46501。
谢谢!
发布于 2011-06-06 07:30:21
使用NSImage并在需要的地方绘制它。例如:
NSString *name = clicked? @"icon-active" : @"icon";
NSImage *image = [NSImage imageNamed:name];
NSPoint p = [self bounds].origin;
[image drawAtPoint:p fromRect:NSZeroRect
operation:NSCompositeSourceOver fraction:1.0];发布于 2011-06-06 09:38:30
如果这是针对状态项的,并且您只想要一个没有编程绘图的图标,则删除视图并设置状态项的image和alternateImage。前者是状态项通常使用的;当用户打开其菜单时,状态项切换到备用图像(如果有)。
https://stackoverflow.com/questions/6245535
复制相似问题