美文网首页
根据星评数字生成相应图片(不想写重复代码,以后粘贴用)

根据星评数字生成相应图片(不想写重复代码,以后粘贴用)

作者: jiangamh | 来源:发表于2016-03-14 20:55 被阅读81次

应用中经常需要根据星评数字生成相应图片,比如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;
        });
        
    });
startL@3x.png
star@3x.png

相关文章

网友评论

      本文标题:根据星评数字生成相应图片(不想写重复代码,以后粘贴用)

      本文链接:https://www.haomeiwen.com/subject/uupflttx.html