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

富文本小星星

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

先看下效果

image.png
image.png

绘制支持小数的星星

  • UIBezierPath绘制图形
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遍历字符串将符合规则的字符串加入数组中
NSRegularExpression *regular = [[NSRegularExpression alloc]initWithPattern:pattern options:NSRegularExpressionCaseInsensitive error:nil];
    NSArray *arr = [regular matchesInString:attr.string options:NSMatchingReportProgress range:NSMakeRange(0, attr.string.length)];
  • NSTextCheckingResult遍历数组, 如果字符串可以直接转换成图片,则直接转换,不需要绘制,否则则转换成float浮点数绘制小星星
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,感谢!

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 1、通过CocoaPods安装项目名称项目信息 AFNetworking网络请求组件 FMDB本地数据库组件 SD...
    阳明AI阅读 16,039评论 3 119
  • 第2章 基本语法 2.1 概述 基本句法和变量 语句 JavaScript程序的执行单位为行(line),也就是一...
    悟名先生阅读 9,675评论 0 13
  • 今天是小升初报名的开始,学校里挤满了往各个地方前来报名的学生和家长。才早上8点,教室门口的长龙已经排到了操...
    云翳黄昏阅读 2,900评论 0 1
  • 马克吐温说过,20年后你不会为你做过的事后悔,会让你后悔的都是你没来得及做的事情。
    魏兆辉阅读 1,820评论 0 0