Problems with cropping a UIImage in Swift [duplicate]

你说的曾经没有我的故事 提交于 2019-12-02 23:21:29

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