Следующая функция изменяет размер изображения. Он принимает два аргумента: изображение и желаемый размер.
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))
ссылка ссылка :: Resize image
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))
Только быстрое примечание на именовании вы используете, классы должны быть названы с UpperCaseLetters в то время как переменные должны использовать lowerCaseLetters. –
Что касается представления изображения, используете ли вы ограничения компоновки? –
Вы совершенно правы в верхнем и нижнем регистре, это, должно быть, была быстрая ошибка на этом изображении. Не в этом контроллере просмотра я пока ничего не делал, кроме добавления изображения и записи этого кода. –