http://blog.csdn.net/fanjunxi1990/article/details/8663914
由于项目需求,需要做一个列表,里面有各个商品的评分,就是app store里面所有app的星级评分
下面是DisplayStarView.h
-
- #import <Foundation/Foundation.h>
-
- @interface DisplayStarView : UIView
- {
- CGFloat _starSize;
- NSInteger _maxStar;
- NSInteger _showStar;
- UIColor *_emptyColor;
- UIColor *_fullColor;
- }
- @property (nonatomic, assign) CGFloat starSize;
- @property (nonatomic, assign) NSInteger maxStar;
- @property (nonatomic, assign) NSInteger showStar;
- @property (nonatomic, retain) UIColor *emptyColor;
- @property (nonatomic, retain) UIColor *fullColor;
- @end
DisplayStarView.m如下
-
- #import "DisplayStarView.h"
-
- @implementation DisplayStarView
- @synthesize starSize = _starSize;
- @synthesize maxStar = _maxStar;
- @synthesize showStar = _showStar;
- @synthesize emptyColor = _emptyColor;
- @synthesize fullColor = _fullColor;
-
- - (id)initWithFrame:(CGRect)frame
- {
- self = [super initWithFrame:frame];
- if (self)
- {
- self.backgroundColor = [UIColor clearColor];
-
- self.starSize = 13.0f;
-
- self.emptyColor = [UIColor colorWithRed:167.0f / 255.0f green:167.0f / 255.0f blue:167.0f / 255.0f alpha:1.0f];
-
- self.fullColor = [UIColor colorWithRed:255.0f / 255.0f green:121.0f / 255.0f blue:22.0f / 255.0f alpha:1.0f];
-
- self.maxStar = 100;
- }
-
- return self;
- }
-
- - (void)drawRect:(CGRect)rect
- {
-
- CGContextRef context = UIGraphicsGetCurrentContext();
-
- NSString* stars = @"★★★★★";
-
- rect = self.bounds;
- UIFont *font = [UIFont boldSystemFontOfSize:_starSize];
- CGSize starSize = [stars sizeWithFont:font];
- rect.size=starSize;
- [_emptyColor set];
- [stars drawInRect:rect withFont:font];
-
- CGRect clip = rect;
- clip.size.width = clip.size.width * _showStar / _maxStar;
- CGContextClipToRect(context,clip);
- [_fullColor set];
- [stars drawInRect:rect withFont:font];
- }
-
- - (void)dealloc
- {
- [_emptyColor release];
- [_fullColor release];
-
- [super dealloc];
- }
-
- @end
需要怎么去使用呢?很简单,值需要知道评分是多少就OK啦,比如
- DisplayStarView *sv = [[DisplayStarView alloc]initWithFrame:CGRectMake(90, 90, 200, 40)];
- [self.view addSubview:sv];
- sv.showStar = 4.2*20;
- [sv release];
-
-
- DisplayStarView *sv1 = [[DisplayStarView alloc]initWithFrame:CGRectMake(90, 90+40, 200, 40)];
- [self.view addSubview:sv1];
- sv1.showStar = 2.5 * 20;
- [sv1 release];
-
-
- DisplayStarView *sv2 = [[DisplayStarView alloc]initWithFrame:CGRectMake(90, 90+40+40, 200, 40)];
- [self.view addSubview:sv2];
- sv2.showStar = 4.8 * 20;
- [sv2 release];
运行结果如图所示:

如何在iPhone 显示一个 星级评分
原文:http://www.cnblogs.com/itlover2013/p/4855127.html