我有一个来自一个类的视图,我想将角半径设置为等于宽度的一半。
宽度是使用autolayout创建的计算属性。所以通常我会在viewWillLayoutSubviews()
中设置角半径属性,如此
override func viewWillLayoutSubviews() {
super.viewWillLayoutSubviews()
c.largeProfileImage.layer.cornerRadius = c.largeProfileImage.frame.width / 2
}
但是largeProfileImage不是它在viewdidLoad之后调用的初始视图,我在点击手势上为它设置动画。下面是视图在屏幕上的动画。它是在同一个函数中创建的。
//I tried setting the cornerRadius here as well but it isn't setting.
//c.largeProfileImage.layer.cornerRadius = c.largeProfileImage.frame.width / 2
self.view.layoutIfNeeded()
UIView.animate(withDuration: 0.5, delay: 0, usingSpringWithDamping: 0.8, initialSpringVelocity: 0, options: .curveEaseOut, animations: {
self.profileImageContainerCenterY?.constant = -(c.profileImageContainer.frame.height) * 2
self.profileSettingsContainerCenterY?.constant = 0
c.profileSettingsContainer.alpha = 1
c.largeProfileImage.alpha = 1
self.view.layoutIfNeeded()
}, completion: { (completed) in
self.view.layoutIfNeeded()
})
修改
这是profileImage
let largeProfileImage: UIImageView = {
let pv = UIImageView()
pv.contentMode = .scaleAspectFill
pv.layer.masksToBounds = true
pv.clipsToBounds = true
pv.image = UIImage(named: "user")
pv.translatesAutoresizingMaskIntoConstraints = false
return pv
}()
答案 0 :(得分:2)
我能够成功调试此问题。
由于宽度是计算属性,因此在布局布局之前它为0意味着
c.largeProfileImage.layer.cornerRadius = c.largeProfileImage.frame.width / 2
self.view.layoutIfNeeded()
导致圆角半径为零。
所以解决方案......
之后调用它的宽度是在计算宽度后设置角半径。
self.view.layoutIfNeeded()
c.largeProfileImage.layer.cornerRadius = c.largeProfileImage.frame.width / 2
答案 1 :(得分:0)
为了正确的动画,改变这样的序列。
self.profileImageContainerCenterY?.constant = -(c.profileImageContainer.frame.height) * 2
self.profileSettingsContainerCenterY?.constant = 0
UIView.animate(withDuration: 0.5, delay: 0, usingSpringWithDamping: 0.8, initialSpringVelocity: 0, options: .curveEaseOut, animations: {
c.profileSettingsContainer.alpha = 1
c.largeProfileImage.alpha = 1
self.view.layoutIfNeeded()
}, completion: nil)
答案 2 :(得分:0)
以下三行是获得圆形图像所必需的 -
image.layer.cornerRadius = image.frame.width / 2
image.layer.masksToBounds = false
image.clipsToBounds = true
您可能会看到一个四舍五入的UIImage
,但您可能还会注意到圆圈内的图像平方并解决了您可能已经使用contentMode
。大部分时间.scaleAspectFill
都能胜任。