在Swift中裁剪UIImage的问题

我正在编写一个应用程序,它会拍摄一张图像,然后剪出除了图像中心的一个矩形之外的所有东西。 (SWIFT)我不能让裁剪function工作。 这是我现在所拥有的:

func cropImageToBars(image: UIImage) -> UIImage { let crop = CGRectMake(0, 200, image.size.width, 50) let cgImage = CGImageCreateWithImageInRect(image.CGImage, crop) let result: UIImage = UIImage(CGImage: cgImage!, scale: 0, orientation: image.imageOrientation) UIImageWriteToSavedPhotosAlbum(result, self, nil, nil) return result } 

我看了很多不同的指南,但没有一个似乎为我工作。 有时图像旋转了90度,我不知道为什么这样做。

如果您想使用扩展名,只需简单地将其添加到文件中,开始或结束。 你可以为这样的代码创build一个额外的文件。

Swift 3.0

 extension UIImage { func crop( rect: CGRect) -> UIImage { var rect = rect rect.origin.x*=self.scale rect.origin.y*=self.scale rect.size.width*=self.scale rect.size.height*=self.scale let imageRef = self.cgImage!.cropping(to: rect) let image = UIImage(cgImage: imageRef!, scale: self.scale, orientation: self.imageOrientation) return image } } let myImage = UIImage(named: "Name") myImage?.crop(rect: CGRect(x: 0, y: 0, width: 50, height: 50)) 

对于图像的中心部分的裁剪:

 let imageWidth = 100.0 let imageHeight = 100.0 let width = 50.0 let height = 50.0 let origin = CGPoint(x: (imageWidth - width)/2, y: (imageHeight - height)/2) let size = CGSize(width: width, height: height) myImage?.crop(rect: CGRect(origin: origin, size: size))