作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
要在 Dock 中向应用程序添加徽章很简单,只需调用 [NSDockTile setBadgeLabel]
即可。但我想向通用 NSView 添加徽章。有什么办法可以做到这一点吗?或者如果做不到这一点,您如何绘制一个,使其看起来与系统 UI 的其余部分保持一致?
最佳答案
没有内置方法可以在 NSView
上绘制徽章,因此您应该自己绘制它。这是我绘制徽章的代码:
- (void)drawBadgeImageWithText:(NSString*)text atPoint:(NSPoint)point
{
NSSize badgeSize = [self badgeSizeForString:text];
NSRect badgeRect = NSMakeRect(point.x - badgeSize.width, point.y - badgeSize.height, badgeSize.width, badgeSize.height);
[NSGraphicsContext saveGraphicsState];
// Set a shadow
NSShadow* shadow = [[NSShadow alloc] init];
shadow.shadowColor = [[NSColor blackColor] colorWithAlphaComponent:0.4];
shadow.shadowBlurRadius = 1;
shadow.shadowOffset = NSMakeSize(0, -1);
[shadow set];
// Draw white border
NSBezierPath* path = [NSBezierPath bezierPathWithRoundedRect:badgeRect xRadius:badgeSize.height / 2.0 yRadius:badgeSize.height / 2.0];
[[NSColor whiteColor] setFill];
[path fill];
[NSGraphicsContext restoreGraphicsState];
// Fill the background with red gradient
badgeRect = NSInflateRect(badgeRect, -1.5, -1.5);
path = [NSBezierPath bezierPathWithRoundedRect:badgeRect xRadius:badgeSize.height / 2.0 yRadius:badgeSize.height / 2.0];
[[NSColor colorWithCalibratedRed:192.0 / 255.0 green:0.0 blue:0.0 alpha:1.0] setFill];
[path fill];
NSGradient* gradient = [[NSGradient alloc] initWithStartingColor:[NSColor colorWithCalibratedRed:241.0 / 255.0 green:113.0 / 255.0 blue:115.0 / 255.0 alpha:1.0]
endingColor:[NSColor colorWithCalibratedRed:192.0 / 255.0 green:0.0 blue:0.0 alpha:1.0]];
[gradient drawInBezierPath:path angle:-90.0];
// Draw the text
NSMutableParagraphStyle* paragraphStyle = [[NSMutableParagraphStyle alloc] init];
[paragraphStyle setAlignment:NSCenterTextAlignment];
NSDictionary* textAttributes = @{NSForegroundColorAttributeName:[NSColor whiteColor], NSParagraphStyleAttributeName:paragraphStyle};
[text drawInRect:badgeRect withAttributes:textAttributes];
}
- (NSSize)badgeSizeForString:(NSString*)string
{
NSDictionary* attributes = [NSDictionary dictionaryWithObject:[NSFont systemFontOfSize:13] forKey: NSFontAttributeName];
NSSize size = [string sizeWithAttributes:attributes];
// Paddings
size.height += 2.0;
size.width += 12.0;
return size;
}
关于objective-c - 如何在 NSView (Mac OS X) 上显示徽章,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19816239/
我是一名优秀的程序员,十分优秀!