2008-11-03 77 views

回答

22

据我所知,这没有API。但是,使用CoreGraphics(NSBezierPath在iPhone上不可用),你可以很容易地做到这一点。这是在CGPath只有两个弧和一些文字:

CGContextRef  context = UIGraphicsGetCurrentContext(); 
float    radius = bounds.size.height/2.0; 
NSString   *countString = [NSString stringWithFormat: @"%d", count]; 

CGContextClearRect(context, bounds); 

CGContextSetFillColorWithColor(context, ovalColor); 
CGContextBeginPath(context); 
CGContextAddArc(context, radius, radius, radius, M_PI/2 , 3 * M_PI/2, NO); 
CGContextAddArc(context, bounds.size.width - radius, radius, radius, 3 * M_PI/2, M_PI/2, NO); 
CGContextClosePath(context); 
CGContextFillPath(context); 

[[UIColor whiteColor] set]; 

UIFont    *font = [UIFont boldSystemFontOfSize: 14]; 
CGSize    numberSize = [countString sizeWithFont: font]; 

bounds.origin.x = (bounds.size.width - numberSize.width)/2; 

[countString drawInRect: bounds withFont: font]; 
+0

谢谢本。这正是我需要的。 – leonho 2008-11-04 05:11:21

0

NSBezierPath类中有几个方法称为“appendBezierPathWithRoundedRect ....”。

我还没有尝试过自己,但他们可能会工作。值得一试。

-7

还有另一种类型的徽章,您可能已经知道,它是应用程序图标上的“红色”徽章。它们通过执行如下操作来创建:

NSDate *now = [NSDate dateWithTimeIntervalSinceNow:0]; 
NSString *caldate = [[now 
     dateWithCalendarFormat:@"%b" 
     timeZone:nil] description]; 
[self setApplicationBadge:caldate];" 

这将为当前月份设置带有3个字母缩写的徽章。

3

我认为更好的方式来实现的东西非常接近UITabBarItem徽章是使用UIImage stretchableImageWithLeftCapWidth:topCapHeight:方法,其中两个端盖可能是一个发烧友图像和中间将自动拉伸(使用1px宽的图像)以适应将覆盖在顶部的NSString尺寸。

仍然需要获得正确的图像,但可以很容易地从屏幕截图或从PS构建。

1

您可以通过使用简单的UILabel和改变其下层中的cornerRadius轻松,灵活地做到这一点:

#import <QuartzCore/QuartzCore.h> // don't forget! 
// ... 
UILabel *badge = [[UILabel alloc] init]; 
badge.layer.backgroundColor = [UIColor blueColor].CGColor; 
badge.layer.cornerRadius = badge.bounds.size.height/2; 

你可以用我的(小和简单)code for a BadgeLabel class and a matching BadgeTableViewCell class

相关问题