I get images that are in 1920x1080 resolution. I am attempting to crop them to the center square area (ie 1080x1080 square in the center). The resolution may change in the future. Would it be possible to crop the image this way? I have tried a couple things posted on SO, but I always get an image that is 660x1080 if I try to crop then center. Here is an image depicting what I want to achieve.
Basically the red is original, green is what I want, and yellow is just showing mixX and midY lines.
The code I tried.
func imageByCroppingImage(image: UIImage, toSize size: CGSize) -> UIImage{
let newCropWidth: CGFloat?
let newCropHeight: CGFloat?
if image.size.width < image.size.height {
if image.size.width < size.width {
newCropWidth = size.width
} else {
newCropWidth = image.size.width
}
newCropHeight = (newCropWidth! * size.height) / size.width
} else {
if image.size.height < size.height {
newCropHeight = size.height
} else {
newCropHeight = image.size.height
}
newCropWidth = (newCropHeight! * size.width) / size.height
}
let x = image.size.width / 2.0 - newCropWidth! / 2.0
let y = image.size.height / 2.0 - newCropHeight! / 2.0
let cropRect = CGRect(x: x, y: y, width: newCropWidth!, height: newCropHeight!)
let imageRef = image.cgImage!.cropping(to: cropRect)
let cropped = UIImage(cgImage: imageRef!, scale: 1.0, orientation: .right)
return cropped
}
And then I pass that method a CGSize(1080, 1080). I get an image that is 660, 1080. Any thoughts?
The intent is to crop the image, not to just display it centered.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…