Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Problems with cropping a UIImage in Swift [duplicate]

I'm writing an app that takes an image and crops out everything except for a rectangle in the center of the image. (SWIFT) I can't get the crop function to work though. This is what I have now:

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
  }

I've looked at a lot of different guides but none of them seem to work for me. Sometimes the image is rotated 90 degrees, I have no idea why it does that.

like image 825
mawnch Avatar asked Sep 03 '16 19:09

mawnch


1 Answers

If you would like to use an extension, just simply add it to the file, in the beginning, or the end. You can create an extra file for such code.

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))

for crop of a center portion of an image:

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))
like image 66
pedrouan Avatar answered Sep 19 '22 23:09

pedrouan