使用 url 数据在 TabBar 中快速更改图像的角半径

Swift change corner radius of image in TabBar using url data

提问人:adalovelacy 提问时间:8/27/2023 更新时间:8/27/2023 访问量:14

问:

我正在尝试从 url 检索到的数据更新图像后更改选项卡栏中图像的角半径。

我尝试在viewDidAppear中实现layer.cornerRadius以及viewDidLayoutSubviews()。

图像按预期显示,但无法更改拐角半径。

var profileImageView = UIImageView(frame: CGRect(x: 0, y: 0, width: 30, height: 30))

override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        
        // check users profile image
        if let imageURL = Auth.auth().currentUser?.photoURL {
            
            guard let url = URL(string: imageURL.absoluteString) else { return }

            profileImageView.translatesAutoresizingMaskIntoConstraints = false
            profileImageView.layer.masksToBounds = true
            profileImageView.clipsToBounds = true
            let data = try! Data(contentsOf: url)
            let image = UIImage(data: data)!
            let resized = resizeImage(image: image, targetSize: CGSize(width: 30, height: 30))?.withRenderingMode(.alwaysOriginal)

            profileImageView.image = resized
            //profileImageView.layer.cornerRadius = 30//( imageView.frame.size.width ) / 2
            
            DispatchQueue.main.async {
                self.navigationController?.tabBarController?.tabBar.items![2].image =   self.profileImageView.image
            }
            
        
        }
}

func resizeImage(image: UIImage, targetSize: CGSize) -> UIImage? {
        let size = image.size
        let widthRatio  = targetSize.width  / size.width
        let heightRatio = targetSize.height / size.height
        var newSize: CGSize
        if(widthRatio > heightRatio) {
            newSize = CGSize(width: size.width * heightRatio, height: size.height * heightRatio)
        } else {
            newSize = CGSize(width: size.width * widthRatio, height: size.height * widthRatio)
        }
        let rect = CGRect(x: 0, y: 0, width: newSize.width, height: newSize.height)
        UIGraphicsBeginImageContextWithOptions(newSize, false, 1.0)
        image.draw(in: rect)
        let newImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return newImage
    }
Swift UIImpoment UITabbar UITABBARITEM

评论


答: 暂无答案