2008-11-03 76 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

相關問題