【问题标题】:Issue with image scaling in Swift on iPhoneiPhone 上 Swift 中的图像缩放问题
【发布时间】:2016-03-20 10:48:09
【问题描述】:

我对 swift 还很陌生,目前在尝试缩放图像以适应屏幕的整个宽度时遇到了问题。由于图像的高度不同,如果可能的话,我想简单地将其宽度属性设置为屏幕宽度,并允许相应地缩放高度(它的固有尺寸已设置为“占位符”)。我正在使用以下代码来缩放图像:

imgPrimaryImg.image = ImageHelper.loadImage(product.defaultImage)
imgPrimaryImg.contentMode = UIViewContentMode.ScaleAspectFit

问题是使用 ScaleAspectFit,有很多透明背景(为了清晰起见,我将背景颜色设置为蓝色 - 如果它是透明的,问题仍然存在,我试过了)

Broken image design

无论如何我可以设置它,以便不渲染背景的透明部分(或至少不显示,因为它完全破坏了设计)

不确定是否有帮助,但这是设置的其余部分

Storyboard setup

任何帮助将不胜感激

【问题讨论】:

标签: ios iphone swift uiimageview uiimage


【解决方案1】:

所以,经过进一步研究,我设法找到了一个考虑到我的情况并设法解决问题的问题:

let aspectRatio = image.size.width / image.size.height
let newHeight = desiredWidth / aspectRatio

UIGraphicsBeginImageContext(CGSizeMake(desiredWidth, newHeight))
image.drawInRect(CGRectMake(0, 0, desiredWidth, newHeight))

let scaledImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()

return scaledImage

并将当前屏幕宽度作为“desiredWidth”(UIScreen.mainScreen().bounds.width)传递。

原帖是Rescale image so width is half the size of screen,以防万一有人遇到同样的问题

【讨论】:

    猜你喜欢
    • 2014-07-09
    • 2011-09-22
    • 1970-01-01
    • 2013-09-09
    • 1970-01-01
    • 1970-01-01
    • 2017-12-28
    • 2011-05-19
    • 1970-01-01
    相关资源
    最近更新 更多