Collapse A UIImageView From A Center Point

1.5k Views Asked by At

I have a UIImageView that I want to scale its outter edges towards the center (the top and bottom edges to be precise). The best I am able to get so far is just one edge collapsing into the other (which doesn't move). I want both edges to collapse towards the middle.

I have tried setting the the anchor point to 0.5,0.5 but that doesnt address the issue (nothing changes).

Is there a way to setup an ImageView such that it will scale inwards towards the middle so the outter edges collapse towards the center?

Here was my best attempt:

override public func viewWillAppear(animated: Bool)
    {
        super.viewWillAppear(animated)
        var uimg = UIImage(named: "img.PNG")!
        var img:UIImageView = UIImageView(image: uimg)
        img.layer.anchorPoint = CGPointMake(0.5, 0.5)
        view.addSubview(img)
        UIView.animateWithDuration(5, animations:
            { () -> Void in
                img.frame = CGRectMake(img.frame.origin.x,img.frame.origin.y,img.frame.width, 0)
            })
            { (finished) -> Void in
                //
        }

    }
2

There are 2 best solutions below

2
On BEST ANSWER

You can use scaling using UIView's transform property. It seems like scaling does not allow you to make the value 0 and it goes to the final value without any animation. So, you could basically make the scaling y value negligible like 0.001.

   imageView.transform = CGAffineTransformMakeScale(1, 0.001)

You could also use core animation to scale, using CABasicAnimation, this would be more simpler as this,

    let animation = CABasicAnimation(keyPath: "transform.scale.y")
    animation.toValue = 0
    animation.duration = 2.0
    animation.fillMode = kCAFillModeForwards
    animation.removedOnCompletion = false
    imageView.layer.addAnimation(animation, forKey: "anim")

Or you can also use the approach you have been using, simply setting the frame,

    var finalFrame = imageView.frame
    finalFrame.size.height = 0

    finalFrame.origin.y = imageView.frame.origin.y + (imageView.frame.size.height / 2)

    UIView.animateWithDuration(2.0, animations: { () -> Void in
        self.imageView.frame = finalFrame
    })
1
On

Your new frame has the origin in the same place. You need to move the origin down, at the same time as you reduce the height:

img.frame = CGRectMake(img.frame.origin.x, img.frame.origin.y + (img.frame.size.height/2), img.frame.size.width, 0);