iPhone 8和8 plus上的图像呈现方式不同

时间:2018-01-06 17:15:02

标签: ios swift image image-resizing resizable

我尝试以编程方式添加用作进度条图像背景上方的进度条的图像。

但它在iPhone 8与iPhone 8+上的呈现方式不同: enter image description here

使用的代码如下:

private func updateGauge() {
    // Progress value to apply to not overedge content view
    let applicableProgress = 1.0

    // Get proper image
    self.image = getImageColorFrom(progress: applicableProgress)

    // Progress bar frame
    if let superviewHeight = self.superview?.frame.size.height {

        // Height
        let progressViewHeight = CGFloat(applicableProgress) * (superviewHeight-borderVertical*2)

        // Width
        let progressViewWidth = self.superview!.frame.size.width - (borderHorizontal*2)

        // Build y position
        let yPos = superviewHeight - progressViewHeight

        // Finally set frame
        self.frame = CGRect(x: borderHorizontal-decalageHorizontal, y: yPos-borderVertical+decalageVertical, width: progressViewWidth, height: progressViewHeight)
    }
}

private func getImageColorFrom(progress: Double) -> UIImage {
    let image: UIImage

    // Retrieve the good background color based on progress value
    if progress == 0 {
        image = UIImage()
    }
    else if progress < greenMaxValue {
        image = UIImage(progressBar: ProgressBarColor.Green)// "jaugeverte.png"
    }
    else if progress < orangeMaxValue {
        image = UIImage(progressBar: ProgressBarColor.Orange)// "jaugeorange.png"
    }
    else {
        image = UIImage(progressBar: ProgressBarColor.Red)// "jaugerouge.png"
    }

    // Build resizable image
    return image.resizableImage(withCapInsets: UIEdgeInsets(top: 10, left: 0, bottom: 10, right: 0), resizingMode: .stretch)
}

有关信息,这两个图像都用作IBOutlet,这就是我们在代码中没有addSubview()调用的原因。 我记录了帧大小,结果如下:

progressViewBackgroundFrame (8 / 8+): (17.0, 67.0, 45.0, 460.0) / (17.0, 71.0, 45.0, 525.0)
progressViewFrame (8 / 8+): (8.0, 9.0, 27.0, 443.0) / (8.0, 9.0, 27.0, 508.0)

为什么iPhone 8和8+上的图像呈现方式不同?图像帧是预期的,它是resizableImage函数的问题吗?

提前致谢, 问候。

1 个答案:

答案 0 :(得分:1)

iPhone 8是@2x图像比例因子设备,iPhone 8+是@3x图像比例因子设备。虽然这不会影响我们在Swift中使用的点,但它会影响图像渲染。加大尺寸iPhone的图像像素大小必须比非加iPhone大1.5倍。同时在资产目录中验证您有两个单独的@2x@3x图片。