Cropping center square of UIImage

后端 未结 18 667
日久生厌
日久生厌 2020-12-07 23:09

So here\'s where I\'ve made it so far. I am using a UIImage captured from the camera and can crop the center square when in landscape. For some reason this doesn\'t transl

18条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-07 23:17

    Swift 2 using UIImage Extension

    extension UIImage
    {    
        func imageByCroppingImage(size : CGSize) -> UIImage
        {
            let refWidth : CGFloat = CGFloat(CGImageGetWidth(self.CGImage))
            let refHeight : CGFloat = CGFloat(CGImageGetHeight(self.CGImage))
    
            let x = (refWidth - size.width) / 2
            let y = (refHeight - size.height) / 2
    
            let cropRect = CGRectMake(x, y, size.width, size.height)
            let imageRef = CGImageCreateWithImageInRect(self.CGImage, cropRect)
    
            let cropped : UIImage = UIImage(CGImage: imageRef!, scale: 0, orientation: self.imageOrientation)
    
    
            return cropped
        }
    }
    

提交回复
热议问题