开发者

NSString *text to NSString *icon?

开发者 https://www.devze.com 2023-03-11 01:46 出处:网络
I am making an app that is a standalone menu item and the basis for the code is sample code I found on a website. The sample code uses a number as the menu icon, but I want to change it to an image.

I am making an app that is a standalone menu item and the basis for the code is sample code I found on a website. The sample code uses a number as the menu icon, but I want to change it to an image.

I want it to be like other apps where it shows icon.png when not clicked and icon-active.png when clicked.

The current code is this:

- (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].si开发者_JAVA技巧ze.width - msgSize.width) / 2.0;
msgRect.origin.y = ([self frame].size.height - msgSize.height) / 2.0;

[text drawInRect:msgRect withAttributes:msgAttrs];
}

Also, I found a post describing a method on how to do this, but it did not work for me. The url to that is this: http://mattgemmell.com/2008/03/04/using-maattachedwindow-with-an-nsstatusitem/comment-page-1#comment-46501.

Thanks!


Use an NSImage and draw it where desired. For example:

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];


If this is for a status item and you just want an icon with no programmatic drawing, drop the view and set the status item's image and alternateImage. The former is what the status item uses normally; the status item switches to the alternate image (if it has one) when the user opens its menu.

0

精彩评论

暂无评论...
验证码 换一张
取 消