Problems with cropping a UIImage in Swift [duplicate]

丶灬走出姿态 提交于 2019-12-03 09:11:10

问题


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.


回答1:


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


来源:https://stackoverflow.com/questions/39310729/problems-with-cropping-a-uiimage-in-swift

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!