How to crop the UIImage?

后端 未结 7 1476
南笙
南笙 2020-11-30 01:50

I develop an application in which i process the image using its pixels but in that image processing it takes a lot of time. Therefore i want to crop UIImage (Only middle par

7条回答
  •  执念已碎
    2020-11-30 02:13

    Because I needed it just now, here is M-V 's code in Swift 4:

    func imageWithImage(image: UIImage, croppedTo rect: CGRect) -> UIImage {
    
        UIGraphicsBeginImageContext(rect.size)
        let context = UIGraphicsGetCurrentContext()
    
        let drawRect = CGRect(x: -rect.origin.x, y: -rect.origin.y, 
                              width: image.size.width, height: image.size.height)
    
        context?.clip(to: CGRect(x: 0, y: 0, 
                                 width: rect.size.width, height: rect.size.height))
    
        image.draw(in: drawRect)
    
        let subImage = UIGraphicsGetImageFromCurrentImageContext()
    
        UIGraphicsEndImageContext()
        return subImage!
    }
    

提交回复
热议问题