我从服务器加载了一张图片,并试图将它放在 UITabBarItem
上,但它只显示一个灰色方 block 。我已经将图像渲染模式设置为原始但不起作用...
谢谢你的帮助
downloader.imageDownloader?.downloadImage(with: URL(string: GlobalSetting().initUser().photoPath)!, options: .highPriority, progress: { (receivedSize, expectedSize, url) in
print(receivedSize as Int)
}, completed: { (image, data, error, success) in
let newImage = image?.resizeImageWith(newSize: CGSize(width: 20, height: 20))
newImage?.withRenderingMode(.alwaysOriginal)
self.tabBar.items![1].image = newImage
})
GlobalSetting 是我保存 URL 照片“http://api.humancloudz.com/photo/comp_abc/avatar-A18002.png”的地方
最佳答案
我不知道你的代码哪里有问题,因为我只看到了其中的一部分。我尝试创建 TabBarController,尝试在 viewDidAppear 中加载图像,一切正常。试试我的代码
class TabBarController: UITabBarController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
guard let url = URL(string: "https://homepages.cae.wisc.edu/~ece533/images/airplane.png") else { return }
let data = try! Data(contentsOf: url)
let image = UIImage(data: data)!
let resized = resizeImage(image: image, targetSize: CGSize(width: 20, height: 20))?.withRenderingMode(.alwaysOriginal)
tabBar.items![0].image = resized
tabBar.items![1].image = resized
}
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
}
希望对你有帮助
关于ios - 从服务器加载图像到标签栏项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57289993/