星级评分

2019-02-12  本文已影响1人  小凡凡520
一、背景

许多App都会有评价功能,这个时候或许会需要实现星级评分,下面我们来简单的实现一个星级评分功能。

二、简单案例
1642454-b35609500c0a3253.png 2248583-322b952d34d16407.png
三、案例实现(根据星级浮点值显示星级结果)

前提条件: 准备两张图片,灰色底星级切图以及满星级切图

    @IBOutlet weak var bgImg: UIImageView!
    @IBOutlet weak var frontImg: UIImageView!
    @IBOutlet weak var slider: UISlider!

    fileprivate let bgImgWidth:CGFloat = 240
    fileprivate let originImgName:String = "originImg.png"

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        
        slider.minimumValue = 0
        slider.maximumValue = 1
        slider.addTarget(self, action: #selector(change(value:)), for: .valueChanged)
        
        if let img = UIImage(named: originImgName) {
            let curImg = cutImage(image: img, fractonPart: CGFloat(slider.value))
            frontImg.frame = CGRect(x: frontImg.frame.origin.x, y: frontImg.frame.origin.y, width: bgImgWidth * CGFloat(slider.value), height: frontImg.frame.size.height)
            frontImg.image = curImg
        }
    }

    @objc func change(value:UISlider) {
        if let img = UIImage(named: originImgName) {
            let curImg = cutImage(image: img, fractonPart: CGFloat(value.value))
            frontImg.frame = CGRect(x: frontImg.frame.origin.x, y: frontImg.frame.origin.y, width: bgImgWidth * CGFloat(value.value), height: frontImg.frame.size.height)
            frontImg.image = curImg
        }
    }

    func cutImage(image:UIImage,fractonPart:CGFloat) -> UIImage? {
        let width = image.size.width * fractonPart * image.scale
        let newFrame = CGRect(x: 0, y: 0, width: width, height: image.size.height * image.scale)
        if let source = image.cgImage {
            if let resultImage = source.cropping(to: newFrame) {
                let result = UIImage(cgImage: resultImage, scale: image.scale, orientation: image.imageOrientation)
                return result
            }
        }
        return nil
    }
上一篇下一篇

猜你喜欢

热点阅读