应用中经常需要根据星评数字生成相应图片,比如4.5分,今天写了一个方法,根据数字生成相应的图片。不过只限于0,1,1.5,2.0 ... 5.0。图片资源如下:
static UIImage *halfStarImage = nil;
static CGFloat scale = 0.0;
@implementation HLCommonMethod
+(UIImage*)getStarImageWithStar:(CGFloat)stars
{
NSInteger star = (NSInteger)stars;
UIImage *image = nil;
if (scale == 0.0) {
scale = [UIScreen mainScreen].scale;
}
UIGraphicsBeginImageContextWithOptions(CGSizeMake(80, 20), NO, scale);
int i = 0;
for (i = 0; i< star; i++) {
[[UIImage imageNamed:@"star"] drawInRect:CGRectMake((i % 5) * 15.2 + (i % 5), 2.4, 15.2, 15.2)];
}
if (star < 5)
{
int start = i;
if (star < stars) {
[[UIImage imageNamed:@"startL"] drawInRect:CGRectMake((i % 5) * 15.2 + (i % 5), 2.4, 15.2, 15.2)];
if (!halfStarImage) {
halfStarImage = [self getHalfStarImage];
}
[halfStarImage drawInRect:CGRectMake((i % 5) * 15.2 + (i % 5), 2.4, 15.2, 15.2)];
start = i + 1;
}
for (i = start; i< 5; i++) {
[[UIImage imageNamed:@"startL"] drawInRect:CGRectMake((i % 5) * 15.2 + (i % 5), 2.4, 15.2, 15.2)];
}
}
image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return image;
}
+(UIImage*)getHalfStarImage
{
UIImage *image = [UIImage imageNamed:@"star"];
if (scale == 0.0) {
scale = [UIScreen mainScreen].scale;
}
UIGraphicsBeginImageContextWithOptions(CGSizeMake(15.2, 15.2), NO, scale);
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextTranslateCTM(context, 0, 15.2);
CGContextScaleCTM(context, 1, -1);
CGContextClipToRect(context, CGRectMake(0, 0, 7.6, 15.2));
CGContextDrawImage(context, CGRectMake(0, 0, 15.2, 15.2), image.CGImage);
UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
CGContextRelease(context);
UIGraphicsEndImageContext();
return newImage;
}
@end
使用如下:
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
UIImage *image = [HLCommonMethod getStarImageWithStar:4.5];
dispatch_async(dispatch_get_main_queue(), ^{
_starContentView.image = image;
});
});