Cropping an UIImage

后端 未结 24 1729
轮回少年
轮回少年 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:45

    Best solution for cropping an UIImage in Swift, in term of precision, pixels scaling ...:

    private func squareCropImageToSideLength(let sourceImage: UIImage,
        let sideLength: CGFloat) -> UIImage {
            // input size comes from image
            let inputSize: CGSize = sourceImage.size
    
            // round up side length to avoid fractional output size
            let sideLength: CGFloat = ceil(sideLength)
    
            // output size has sideLength for both dimensions
            let outputSize: CGSize = CGSizeMake(sideLength, sideLength)
    
            // calculate scale so that smaller dimension fits sideLength
            let scale: CGFloat = max(sideLength / inputSize.width,
                sideLength / inputSize.height)
    
            // scaling the image with this scale results in this output size
            let scaledInputSize: CGSize = CGSizeMake(inputSize.width * scale,
                inputSize.height * scale)
    
            // determine point in center of "canvas"
            let center: CGPoint = CGPointMake(outputSize.width/2.0,
                outputSize.height/2.0)
    
            // calculate drawing rect relative to output Size
            let outputRect: CGRect = CGRectMake(center.x - scaledInputSize.width/2.0,
                center.y - scaledInputSize.height/2.0,
                scaledInputSize.width,
                scaledInputSize.height)
    
            // begin a new bitmap context, scale 0 takes display scale
            UIGraphicsBeginImageContextWithOptions(outputSize, true, 0)
    
            // optional: set the interpolation quality.
            // For this you need to grab the underlying CGContext
            let ctx: CGContextRef = UIGraphicsGetCurrentContext()
            CGContextSetInterpolationQuality(ctx, kCGInterpolationHigh)
    
            // draw the source image into the calculated rect
            sourceImage.drawInRect(outputRect)
    
            // create new image from bitmap context
            let outImage: UIImage = UIGraphicsGetImageFromCurrentImageContext()
    
            // clean up
            UIGraphicsEndImageContext()
    
            // pass back new image
            return outImage
    }
    

    Instructions used to call this function:

    let image: UIImage = UIImage(named: "Image.jpg")!
    let squareImage: UIImage = self.squareCropImageToSideLength(image, sideLength: 320)
    self.myUIImageView.image = squareImage
    

    Note: the initial source code inspiration written in Objective-C has been found on "Cocoanetics" blog.

提交回复
热议问题