基于图像的进度条

时间:2019-04-08 16:34:55

标签: swift progress-bar

我需要基于Swift中的图像创建一个进度条。 我在pdf中有2个矢量图像,并具有以下偏好: enter image description here enter image description here

我尝试过的事情:
1)放置背景图片(UIViewImage)
2)放在顶部全图(UIViewImage)
3)将完整图片裁切为50%(image!.cgImage!.cropping(to:cropZone))

我希望看到背景图片的一部分,例如:
enter image description here

但是我看到了完整图片的很大一部分:
enter image description here

这是我的测试代码:

    let cropZone = CGRect(x:30,y:375-96,width:70,height:184)
    let cutImageRef: CGImage = self.coolantFull.image!.cgImage!.cropping(to:cropZone)!
    self.coolantFull.image! = UIImage(cgImage: cutImageRef)

2 个答案:

答案 0 :(得分:0)

对于内容缩放模式,看起来您的顶部图像视图已设置为.fill.aspectFit.aspectFill之一。对于这种情况,您需要确保使用.topLeft来确保内容不会随着遮罩的进行而缩放或移位。

答案 1 :(得分:0)

我为UIImageView编写了扩展程序,该扩展程序基于百分比创建一个新图像并调整其大小。填充从底部到顶部。栅格化的pdf看起来很糟糕,所以现在我使用png @ 1,@ 2,@ 3。

extension UIImageView {
func progress(to _percent: CGFloat, image: UIImage) {
    // restore original image and size in UIImageView
    self.image! = image
    self.frame.size = image.size
    // if less then 0, return 0
    var percent = _percent <= 0 ? 1 : _percent
    // if more then 100, return 100
    percent = percent > 100 ? 100 : percent
    let size = CGSize(width: self.frame.size.width, height: self.frame.size.height/100*percent)
    UIGraphicsBeginImageContextWithOptions(size, false, self.image!.scale)
    self.image!.draw(in: CGRect(x: 0,
                                y: -self.frame.size.height+size.height,
                                width: self.image!.size.width,
                                height: self.image!.size.height))

    let croppedImage = UIGraphicsGetImageFromCurrentImageContext()!
    UIGraphicsEndImageContext()

    self.frame = CGRect(x: self.frame.origin.x,
                        y: self.frame.height-self.frame.height/100*percent,
                        width: self.frame.width,
                        height: self.frame.height/100*percent)
    self.image! = croppedImage
}

使用方法:

@IBOutlet weak var coolantProgress: UIImageView!

let coolantEmptyImage = UIImage.init(named: "coolantFull")
coolantProgress.progress(to: 25, image: coolantEmptyImage!)

enter image description here