Home > Enterprise >  How can I transition a UIImage slowly from top to bottom for applying filter to the image?
How can I transition a UIImage slowly from top to bottom for applying filter to the image?

Time:03-25

I want to make it appear as if my image is slowly getting filtered from top to bottom. I am adding two image views. My processed image is in the background and non-processed in the front. I am making the height of non-processed image 0. Here is my code.

imageView.frame = CGRect(x: 0, y: 100, width: self.view.bounds.size.width, height: 400)
imageView.image = processedImage


let nonProcessedImageView = UIImageView()
nonProcessedImageView.frame = CGRect(x: 0, y: 100, width: self.view.bounds.size.width, height: 400)
nonProcessedImageView.image = nonProcessedImage
view.addSubview(nonProcessedImageView)

UIView.transition(with: nonProcessedImageView,
                  duration: 5.0,
                  animations: {
   nonProcessedImageView.frame = CGRect(x: 0, y: 500, width: self.view.bounds.size.width, height: 0)
   },
                  completion: {_ in
   })

The non processed image does not even appear on top of the processed.

CodePudding user response:

The issue seems to be that changing the y coordinate of the frame in the animation block leads to issues when using the UIView.Animate function.

See this UIImageView animate frames swift iOS

For best results, add the new image view to a UIView and reduce the height of the UIView instead of the UIImageView

var newImageFrame = imageView.frame

let containerView = UIView(frame: newImageFrame)
containerView.clipsToBounds = true

let nonProcessedImageView = UIImageView()
nonProcessedImageView.frame = containerView.bounds
nonProcessedImageView.clipsToBounds = true
nonProcessedImageView.contentMode = .scaleAspectFit // same as original
nonProcessedImageView.image = imageView.image

containerView.addSubview(nonProcessedImageView)
view.addSubview(containerView)

newImageFrame.size.height = 1

imageView.image = processedImage

UIView.animate(withDuration: 3.0) {
    containerView.frame = newImageFrame
}
completion: { (isComplete) in
    if isComplete {
        containerView.removeFromSuperview()
    }
}

This should give you what you want:

UIImageView UIView.animate animate image view height swift iOS

  • Related