星星评分

作者: 随梦而飞飞 | 来源:发表于2016-02-21 00:20 被阅读324次

    星星评分

    • 我们很多时候 为了 UI界面的 简便 美观 ,时常用到 星级评分

    1.实现思路

     主要通过两张  一张图片来遮盖的第二章图片 来实现
    

    2.代码实现

    .h 文件

    #import <UIKit/UIKit.h>
    
    @interface StarView : UIView
    {
     //背景图
     UIImageView *backgroundImageView;
     //前景图
     UIImageView *foregroundImageView;
    }
    //设置星级
    -(void)setStar:(CGFloat)star;
    @end
    

    .m文件实现

    #import "StarView.h"
    @implementation StarView
    -(void)createImage
    {
        backgroundImageView=[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"StarsBackground"]];//白色
        backgroundImageView.frame=CGRectMake(0, 0, 65, 23);
        backgroundImageView.contentMode=UIViewContentModeLeft;
        
        foregroundImageView=[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"StarsForeground"]];//橘红色
        foregroundImageView.frame=CGRectMake(0, 0, 65, 23);
        //设置内容的对齐方式
        foregroundImageView.contentMode=UIViewContentModeLeft;
        //如果子视图超出父视图大小时被裁剪掉
        foregroundImageView.clipsToBounds=YES;
        [self addSubview:backgroundImageView];
        [self addSubview:foregroundImageView];
        self.backgroundColor=[UIColor clearColor];
    }
    
    //给用xib创建这个类对象时用的方法
    -(id)initWithCoder:(NSCoder *)aDecoder
    {
        if (self=[super initWithCoder:aDecoder]) {
            [self createImage];
        }
        return self;
    }
    
    //设置星级
    -(void)setStar:(float)star
    {
        CGRect frame=backgroundImageView.frame;
        
        frame.size.width = frame.size.width * (star / 5);
        
        foregroundImageView.frame=frame;
    }
    
    - (id)initWithFrame:(CGRect)frame
    {
        self = [super initWithFrame:frame];
        if (self) {
            [self createImage];
        }
        return self;
    }
    @end
    

    3.使用方法

     StarView * star=[[StarView alloc] init];
    //设置三颗星 
     [star setStar:3.0f];
    

    效果

    相关文章

      网友评论

        本文标题:星星评分

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