0

I am creating a app where you can crop multiple images to one specific size.

I have a array with multiple images. The images of the array were displayed on a view, where I can drag them inside the view. I am using the same image twice. It look like this:

enter image description here

I also have a crop view (displays red only for demonstration). The images should be crop to this size of the crop view:

enter image description here

The end result look like this:

enter image description here

There were a few problems. I don't understand why the image is rotated. It also seems the image is not cropped to the crop view that I created (the red view). Also the images should have a slight delay, because I drag each of them to a other place in the view.

The method that I am using is from apples documentation:

let cropRect = CGRect(x: cropView.frame.origin.x, y: cropView.frame.origin.y, width: cropView.frame.width, height: cropView.frame.height)

        let croppedImage = ImageCrophandler.sharedInstance.cropImage(imageContentView[i].image!, toRect: cropRect, viewWidth: cropView.frame.width, viewHeight: cropView.frame.height)

        print(croppedImage)

        arrayOfCropedImages.append(croppedImage!)

    func cropImage(_ inputImage: UIImage, toRect cropRect: CGRect, viewWidth: CGFloat, viewHeight: CGFloat) -> UIImage? {
    let imageViewScale = max(inputImage.size.width / viewWidth,
                             inputImage.size.height / viewHeight)

    // Scale cropRect to handle images larger than shown-on-screen size
    let cropZone = CGRect(x:cropRect.origin.x * imageViewScale,
                          y:cropRect.origin.y * imageViewScale,
                          width:cropRect.size.width * imageViewScale,
                          height:cropRect.size.height * imageViewScale)

    // Perform cropping in Core Graphics
    guard let cutImageRef: CGImage = inputImage.cgImage?.cropping(to:cropZone)
    else {
        return nil
    }

    // Return image to UIImage
    let croppedImage: UIImage = UIImage(cgImage: cutImageRef)


    return croppedImage
}
adri567
  • 533
  • 5
  • 20
  • You need to create a new image context and draw your image in it (render it) before cropping it. When you get a CGImage from your image you are discarding its metadata (and its orientation). https://stackoverflow.com/questions/60065539/how-to-crop-wide-images-in-swift-without-stretching/60069492#comment106260487_60069492 – Leo Dabus Feb 29 '20 at 13:58
  • ok, I give it a try. I hope that solve the problem. – adri567 Mar 01 '20 at 11:51
  • could this be a problem that the image is not the full hight of the view? There is a green bar on top and on bottom. The image view has the property .aspectFit – adri567 Mar 01 '20 at 12:28

0 Answers0