Home > Net >  Crop or trim image in Swift, but give the same dimension
Crop or trim image in Swift, but give the same dimension

Time:04-28

I have an image, by example width: 1000, height: 2000

If I crop (or trim) this image by delete the last 500 pixels of the bottom, the result is an image of 1000 X 1500 pixels.

I would like to have a final image of 1000 X 2000 pixels, with the last 500 bottom pixels transparents.

Any help on this is really appreciated

CodePudding user response:

You can use an extension like this:

extension UIImage {
    func clearRect(_ r: CGRect) -> UIImage {
        let renderer = UIGraphicsImageRenderer(size: size)
        let image = renderer.image { (context) in
            // draw the full image
            draw(at: .zero)
            let pth = UIBezierPath(rect: r)
            context.cgContext.setFillColor(UIColor.clear.cgColor)
            context.cgContext.setBlendMode(.clear)
            // "fill" the rect with clear
            pth.fill()
        }
        return image
    }
}

Then to turn the "bottom 500 pixels" transparent, call it like this:

// make sure we have an image
guard let img = UIImage(named: "image1000x2000") else {
    fatalError("Could not load image!")
}
    
// create a new UIImage with the bottom 500 transparent
let newImg = img.clearRect(CGRect(x: 0, y: 1500, width: 1000, height: 500))
    

CodePudding user response:

func cropImage(uiImage: UIImage) -> Image {
        guard let cgImage = uiImage.cgImage else {return Image("CameraGuid")}
        let sideLength = min(
            uiImage.size.width,
            uiImage.size.height
        )
        let sourceSize = uiImage.size
        let xOffset = (sourceSize.width - sideLength) / 2.0
        let yOffset = (sourceSize.height/2) - (sourceSize.height / 6)
        
        let height = ((sourceSize.height/2)   (sourceSize.height / 6)) - yOffset
        let cropRect = CGRect(
            x: xOffset,
            y: yOffset,
            width: sideLength,
            height: height
        ).integral
        let croppedCGImage = cgImage.cropping(
            to: cropRect
        )!
        let draft = UIImage(cgImage: croppedCGImage)
        return Image(uiImage: draft)
    }
  • Related