图片在 iPhone 8 和 8 plus 上呈现不同

Image renders differently on iPhone 8 and 8 plus

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

但它在 iPhone 8 和 iPhone 8+ 上呈现不同:

使用的代码如下:

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函数的问题吗?

提前致谢, 问候。

iPhone 8 是 @2x 图像比例因子设备,iPhone 8+ 是 @3x 图像比例因子设备。虽然这不会影响我们在 Swift 中使用的点,但它会影响图像渲染。大尺寸 iPhones 的图像的像素尺寸必须比非大尺寸 iPhones 的图像大 1.5 倍。还要在您的资产目录中验证 @2x@3x.

有两个单独的图像