iOS开发 支持富文本的可小数的星星评分

2018-09-13  本文已影响0人  YjjTT

富文本小星星

支持小数和富文本的星星评分,目前不支持点击,只支持显示

先看下效果

image.png image.png

绘制支持小数的星星

UIBezierPath *holePath = [UIBezierPath bezierPathWithRect:CGRectMake(0, 0, grayIV.bounds.size.width*decimal, grayIV.bounds.size.height)];
        CAShapeLayer *maskLayer = [CAShapeLayer layer];
        [maskLayer setFillRule:kCAFillRuleEvenOdd];
        maskLayer.path = holePath.CGPath;

富文本显示星星

NSString *pattern = @"\\[[0-9a-zA-Z\\u4e00-\\u9fa5\\d*(\\.\\d*)?)[M|G]B]+\\]";
NSRegularExpression *regular = [[NSRegularExpression alloc]initWithPattern:pattern options:NSRegularExpressionCaseInsensitive error:nil];
    NSArray *arr = [regular matchesInString:attr.string options:NSMatchingReportProgress range:NSMakeRange(0, attr.string.length)];
for (NSTextCheckingResult *result in arr) {
        NSString *matchstring = [attr.string substringWithRange:result.range];
        NSTextAttachment *attachment = [[NSTextAttachment alloc]init];
        if ([[EMOJI allKeys] containsObject:matchstring]) {
            attachment.image = [UIImage imageNamed:EMOJI[matchstring]];
            attachment.bounds = CGRectMake(0, -2.0, 16.0, 16.0);
            [imageArr insertObject:attachment atIndex:0];
            [rangeArr insertObject:result atIndex:0];
        }else{
            NSRange startRange = [matchstring rangeOfString:@"["];
            NSRange endRange = [matchstring rangeOfString:@"]"];
            NSRange range = NSMakeRange(startRange.location + startRange.length, endRange.location - startRange.location - startRange.length);
            NSString *resultStr = [matchstring substringWithRange:range];
            float degree = [resultStr floatValue];
            UIImage *image = [TurnViewToImage turnToImageByScore:degree];
            attachment.image = image;
            attachment.bounds = CGRectMake(0, -2.0, 16.0, 16.0);
            [imageArr insertObject:attachment atIndex:0];
            [rangeArr insertObject:result atIndex:0];
        }
    }
 for (NSTextCheckingResult *result in rangeArr) {
        NSTextAttachment *attchment = imageArr[i];
        [attr replaceCharactersInRange:result.range withAttributedString:[NSAttributedString attributedStringWithAttachment:attchment]];
    }

小结

GITHU地址
喜欢的给个star,感谢!

上一篇下一篇

猜你喜欢

热点阅读