星星评分控件TQStarRatingView揭秘!(一)

作者: wMellon | 来源:发表于2016-05-02 22:20 被阅读1157次

    今天为大家带来一个iOS星级评分控件的实现,欢迎拍砖。

    在github上搜索iOS星级评分控件,可以看到TQStarRatingView是排名比较靠前的,所以今天就以这个为例来说明iOS星级评分控件的实现。TQStarRatingView在github的地址:https://github.com/TinyQ/TQStarRatingView

    首先就是如何能够实现单个星星颜色的变化。

    要弄懂这个问题,那么就应该先知道展示的view是张什么样的。

    打开TQStarRatingView.m文件,找到commonInit方法,如下:

    - (void)commonInit

    {

    self.starBackgroundView = [self buidlStarViewWithImageName:kBACKGROUND_STAR];

    self.starForegroundView = [self buidlStarViewWithImageName:kFOREGROUND_STAR];

    [self addSubview:self.starBackgroundView];

    [self addSubview:self.starForegroundView];

    }

    从这里可以看到生成了两个view,starBackgroundView为背景(暗淡的星星),而starForegroundView为前景(高亮的星星)。再找到生成这两个view的方法buidlStarViewWithImageName

    - (UIView *)buidlStarViewWithImageName:(NSString *)imageName

    {

    CGRect frame = self.bounds;

    UIView *view = [[UIView alloc] initWithFrame:frame];

    view.clipsToBounds = YES;

    CGFloat starsWidth = frame.size.width - (_numberOfStar - 1) * divisionWidth;

    for (int i = 0; i < self.numberOfStar; i ++)

    {

    UIImageView *imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:imageName]];

    imageView.frame = CGRectMake(i / self.numberOfStar * starsWidth + i * divisionWidth, 0, starsWidth / self.numberOfStar, frame.size.height);

    [view addSubview:imageView];

    }

    return view;

    }

    可以看到其实背景view和前景view的frame是完全一样的,没有区别。纳尼!其实就是两个形状大小一模一样的,一个覆盖掉另外一个,高亮星星覆盖掉了暗淡星星~~~这么说来我们看到的星级的效果就应该是要显示多少颗星的时候,把前景的宽度设置为对应的大小,然后下面的暗淡的星星就显示出来了,是不是这样,咱接着往下看。

    接下来我们可以看到有两个设置控件分数的方法,大致代码如下:

    - (void)setScore:(float)score withAnimation:(bool)isAnimate completion:(void (^)(BOOL finished))completion

    {

    NSAssert((score >= 0.0)&&(score <= 1.0), @"score must be between 0 and 1");

    if (score < 0)

    {

    score = 0;

    }

    if (score > 1)

    {

    score = 1;

    }

    CGPoint point = CGPointMake(score * self.frame.size.width, 0);

    //省略部分代码

    [self changeStarForegroundViewWithPoint:point];

    }

    /**

    *  通过坐标改变前景视图

    *

    *  @param point 坐标

    */

    - (void)changeStarForegroundViewWithPoint:(CGPoint)point

    {

    CGPoint p = point;

    if (p.x < 0)

    {

    p.x = 0;

    }

    if (p.x > self.frame.size.width)

    {

    p.x = self.frame.size.width;

    }

    NSString * str = [NSString stringWithFormat:@"%0.2f",p.x / self.frame.size.width];

    float score = [str floatValue];

    p.x = score * self.frame.size.width;

    self.starForegroundView.frame = CGRectMake(0, 0, p.x, self.frame.size.height);

    //省略部分代码

    }

    score是一个浮点数,大小限制为0-1之间,所以其实这是个百分比。然后会根据这个百分比计算要显示的高亮的星星的宽度是多少,来设置starForegroundView显示的宽度(frame.x从0开始)。果然跟我们上面的猜测是一样的,并且这种方式的话,可以满足我们对分数设置的大多数要求,如:4分、4.5分甚至4.1分这种都能轻松搞定。

    相关文章

      网友评论

        本文标题:星星评分控件TQStarRatingView揭秘!(一)

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