다음 함수는 이미지의 크기를 조정. 이미지와 원하는 크기의 두 가지 인수가 필요합니다.
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
스위프트 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))
사용하는 이름 지정 규칙에 그냥 빨리 메모, 클래스는 lowerCaseLetters를 사용해야하는 변수 동안 UpperCaseLetters로 이름을 지정해야합니다. –
이미지보기와 관련하여 레이아웃 제약 조건을 사용하고 있습니까? –
당신은 대문자와 소문자에 대해 완전히 옳았습니다.이 이미지에서 실수 였을 것입니다. 이 View Controller에서는 Image View를 추가하고이 코드를 작성하는 것을 제외하고는 지금까지 아무 것도하지 않았습니다. –