问题描述
限时送ChatGPT账号..我正在尝试创建一个圆形图像,并且我已经实现了正确的代码,但我不知道为什么它下面没有四舍五入是我的代码
I am trying to create a circular image and I have implemeted the right code but I do not know why it does not get rounded below is my code
lazy var profileImage: UIImageView = {
let image = UIImageView()
image.translatesAutoresizingMaskIntoConstraints = false
image.layer.borderColor = UIColor.blue.cgColor
image.layer.borderWidth = 1.5
image.image = UIImage(named: "prof.jpg")
image.contentMode = .scaleAspectFit
image.layer.cornerRadius = image.frame.size.width / 2
image.clipsToBounds = true
return image
}()
我的限制是
fileprivate func layout() {
view.addSubview(profileImage)
NSLayoutConstraint.activate([
profileImage.centerXAnchor.constraint(equalTo: view.centerXAnchor),
profileImage.centerYAnchor.constraint(equalTo: view.centerYAnchor),
profileImage.heightAnchor.constraint(equalToConstant: 200),
profileImage.widthAnchor.constraint(equalToConstant: 200),
])
}
layout() 然后被添加到 viewDidLoad
layout() is then added to viewDidLoad
推荐答案
当 UIImageView 初始化时,你没有给它一个框架,所以它使用 .zero
作为默认值.这意味着当您访问 image.frame.size.width
时,您得到的值为 0.
You’re not giving your UIImageView a frame when it’s initialised so it uses .zero
as a default. This means that when you access image.frame.size.width
you are getting a value of 0.
我的建议是将您的 image.layer.cornerRadius = image.frame.size.width/2
移动到 UIViewController 上的
类.viewDidLayoutSubviews
覆盖
What I would suggest is to move your image.layer.cornerRadius = image.frame.size.width / 2
into the viewDidLayoutSubviews
override on your UIViewController
class.
您还可以创建一个自定义类来继承 UIImageView
并实现相同的逻辑.UIImageView
的 override
将是 layoutSubviews
.
You could also create a custom class that subclasses UIImageView
and implements the same logic. The override
for UIImageView
would be layoutSubviews
.
这篇关于UIImageview 没有变得四舍五入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
更多推荐
[db:关键词]
发布评论