2016-09-03 68 views
8

我正在编写一个应用程序,该应用程序拍摄图像并裁剪出除图像中心的矩形以外的所有内容。 (SWIFT)我无法使裁切功能正常工作。这是我现在有:在Swift中裁剪UIImage的问题

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度,我不知道为什么它会这样做。

+0

欢迎堆栈溢出。在您提出问题之前,请检查本网站有哪些有用的功能。 http://stackoverflow.com/questions/158914/cropping-an-uiimage/29294333#29294333 – pedrouan

+0

看起来像一个类似的问题,但我有问题与斯威夫特,而不是Objective-C。 – mawnch

+0

还有许多快速解决方案。这看起来最好:http://stackoverflow.com/a/30403863/661022 – pedrouan

回答

15

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

夫特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)) 
+0

我在最新的Swift 3.0中发布了这个例子。如果您使用旧版本,复制粘贴将需要一些更正。 – pedrouan

+0

裁剪似乎工作,但我不能让它裁剪我真正想要的图像部分。例如,参数(50,50,500,500)从屏幕右上角返回图像的一部分,这对我来说没有意义。如果我想在屏幕中间有一个矩形(有点像这个http://imgur.com/a/vOMsb)矩形参数应该是什么? – mawnch

+0

@KaviRamamurthy我已经更新了我的答案。 – pedrouan