动画 UIImageView 高度和宽度变化

问题描述 投票:0回答:1

我的目标是动画 UIImageView 从左上角到视图中心的过渡。它还必须将宽度和高度更改为屏幕宽度,并将角半径更改为零。

如何修改以下代码以便 UIImageView 更改其宽度和高度:

    private func imageAnimates() {
        UIView.animate(
            withDuration: 0.5,
            delay: 0.0,
            options: .curveLinear
        ) {
            self.userImage.layer.cornerRadius = 0
            self.userImage.center = CGPoint(x: self.view.center.x, y: self.view.center.y)
        } completion: { finished in
            print("Image animated")
        }
    }

UPD:根据 vaibhav sharma 的回答,我将代码更新为:

        UIView.animate(
            withDuration: 0.5,
            delay: 0.0,
            options: .curveLinear
        ) {
            self.userImage.alpha = 1.0
            self.userImage.layer.cornerRadius = 0
            self.userImage.frame = CGRect(
                 x: (screenWidth - finalWidth) / 2,
                 y: (self.view.frame.size.height - finalHeight) / 2,
                 width: finalWidth,
                 height: finalHeight
             )
        } completion: { finished in
            print("Image animated")
        } 

但是我得到的结果并不是我所期望的。这是屏幕录制:https://sendvid.com/i1fxbf0y。看起来图像现在从左上角的小图片变成了原来的框架和位置。它甚至没有移动到中心。

swift uiview uikit uianimation
1个回答
0
投票

根据我的理解,可能是我错了,请尝试

private func imageAnimates() {
        // Calculate the final width and height to match the screen width
        let screenWidth = self.view.frame.size.width
        let finalWidth = screenWidth
        let finalHeight = screenWidth * (self.userImage.frame.size.height / self.userImage.frame.size.width)
        
        UIView.animate(
            withDuration: 0.5,
            delay: 0.0,
            options: .curveLinear
        ) {
            // Update the corner radius to zero
            self.userImage.layer.cornerRadius = 0
            
            // Update the frame to the final width and height and center it
            self.userImage.frame = CGRect(
                x: (screenWidth - finalWidth) / 2,
                y: (self.view.frame.size.height - finalHeight) / 2,
                width: finalWidth,
                height: finalHeight
            )
        } completion: { finished in
            print("Image animated")
        }
    }
© www.soinside.com 2019 - 2024. All rights reserved.