應用中經(jīng)常需要根據(jù)星評數(shù)字生成相應圖片,比如4.5分壕鹉,今天寫了一個方法剃幌,根據(jù)數(shù)字生成相應的圖片。不過只限于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;
});
});