UIImageview 没有变得四舍五入

编程入门 行业动态 更新时间:2024-10-27 19:23:13
本文介绍了UIImageview 没有变得四舍五入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时送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 并实现相同的逻辑.UIImageViewoverride 将是 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:关键词]

本文发布于:2023-04-29 03:39:43,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1184024.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:四舍五入   UIImageview

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!