2

I have the following Swift code inside a function that splits an image in half vertically:

let myImage = imageView.image!

let newWidth = (myImage.size.width) / 2
let newHeight = myImage.size.height
var cropRect: CGRect = CGRectMake(0.0, 0.0, newWidth, newHeight)

var tempImage: CGImageRef = CGImageCreateWithImageInRect(myImage.CGImage!, cropRect)

let newImage: UIImage = UIImage(CGImage: tempImage)!

println("Original Image: \(myImage.size)")
println("New Image: \(newImage.size)")

imageView.image! = newImage

The original UIImage is being displayed in a UIImageView, but I would like to display the new cropped UIImage in the UIImageView after I create it so that I can see what it looks like.

My last line of code imageView.image! = newImage did not work so I am trying to find a new solution. I have looked through the documentation for UIImageView but there doesn't seem to be a straight forward method that changes the image.

4
  • for me that code totally works! Apr 26, 2015 at 21:27
  • me too, I'd be inclined to think it's a problem with the image adjustment code first. But it's late and I'm too tired to grok it further. Apr 26, 2015 at 21:30
  • This worked once I removed the unwrap (!) from imageView.image. I'm not sure why, my understanding of Optionals is still vey basic.
    – steveclark
    Apr 26, 2015 at 21:37
  • my understand is: imageView.image! = imageView.image! = newImage 1. imageView.image! reproduce a new var 2. then you assign newImage to the new var, so your imageView's property image is not set to newImage.
    – Hugo
    Apr 27, 2015 at 2:07

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Browse other questions tagged or ask your own question.