Cropping an UIImage

后端 未结 24 2262
轮回少年
轮回少年 2020-11-22 02:45

I\'ve got some code that resizes an image so I can get a scaled chunk of the center of the image - I use this to take a UIImage and return a small, square repre

24条回答
  •  感动是毒
    2020-11-22 03:39

    Swift 3 version

    func cropImage(imageToCrop:UIImage, toRect rect:CGRect) -> UIImage{
        
        let imageRef:CGImage = imageToCrop.cgImage!.cropping(to: rect)!
        let cropped:UIImage = UIImage(cgImage:imageRef)
        return cropped
    }
    
    
    let imageTop:UIImage  = UIImage(named:"one.jpg")! // add validation
    

    enter image description here

    with help of this bridge function CGRectMake -> CGRect (credits to this answer answered by @rob mayoff):

     func CGRectMake(_ x: CGFloat, _ y: CGFloat, _ width: CGFloat, _ height: CGFloat) -> CGRect {
        return CGRect(x: x, y: y, width: width, height: height)
    }
    

    The usage is:

    if var image:UIImage  = UIImage(named:"one.jpg"){
       let  croppedImage = cropImage(imageToCrop: image, toRect: CGRectMake(
            image.size.width/4,
            0,
            image.size.width/2,
            image.size.height)
        )
    }
    

    Output:

    enter image description here

提交回复
热议问题