55

我需要从 url 加载图像并将其设置在 UIImageView 中;问题是我不知道图像的确切尺寸,那我怎样才能正确显示图像呢?

4

9 回答 9

119

只需使用 UIImage 的 size 属性即可,例如:

NSURL *url = [NSURL URLWithString:path];
NSData *data = [NSData dataWithContentsOfURL:url];
UIImage *img = [[UIImage alloc] initWithData:data];
CGSize size = img.size;
于 2012-06-10T21:40:17.903 回答
14

迅速:

var url = NSURL.URLWithString("http://www.example.com/picture.png")
var data = NSData(contentsOfURL : url)
var image = UIImage(data : data)
image.size // if you need it
于 2014-09-08T18:26:02.600 回答
9

快速关于使用选项:

var url:NSURL? = NSURL(string: imageString)
var data:NSData? = NSData(contentsOfURL : url!)
var image = UIImage(data : data!)
于 2015-01-07T15:32:46.757 回答
8

在 SWIFT 3.0 中

主线程必须始终保持空闲,以便为用户界面和用户交互提供服务。

class ViewController: UIViewController {

@IBOutlet weak var imageView: UIImageView!

private func fetchImage() {
    let imageURL = URL(string: "https://i.stack.imgur.com/9z6nS.png")
    var image: UIImage?
    if let url = imageURL {
        //All network operations has to run on different thread(not on main thread).
        DispatchQueue.global(qos: .userInitiated).async {
            let imageData = NSData(contentsOf: url)
            //All UI operations has to run on main thread.
            DispatchQueue.main.async {
                if imageData != nil {
                    image = UIImage(data: imageData as! Data)
                    self.imageView.image = image
                    self.imageView.sizeToFit()
                } else {
                    image = nil
                }
            }
        }
    }
}

override func viewDidLoad() {
    super.viewDidLoad()
    fetchImage()
}

}
于 2016-12-18T11:33:53.060 回答
1

要使用 Kingfisher 库下载异步图像,您可以按照此步骤操作,网址:https ://github.com/onevcat/Kingfisher :

 func imageFromUrl(_ urlString: String) {
        if let url = URL(string: urlString) {
            ImageDownloader.default.downloadImage(with: url, options: [], progressBlock: nil) {
                (image, error, url, data) in
                DispatchQueue.main.async {
                    self.imageView.image = image
                }
            }
        }
    }

您还可以使用默认 URLSession.shared.dataTask 下载图像

 func imageFromUrl(_ urlString: String) {
        if let url = URL(string: urlString) {
            let request = URLRequest(url: url)
            URLSession.shared.dataTask(with: request) {(data,response,error) in
                if let imageData = data as Data? {
                    if let img = UIImage(data: imageData){
                       DispatchQueue.main.async {
                       self.imageView.image = img
                       }
                    }
                }
            }
        }
    }
于 2017-05-23T11:49:14.270 回答
0

Swift 安全代码版本:

private func loadImage(from url:URL) -> UIImage? {
    let imageData: Data
    
    do {
        imageData = try Data(contentsOf: url)
    } catch {
        return nil
    }
    
    return UIImage(data: imageData)
}

private func loadImage(from urlString:String) -> UIImage? {
    guard let url = URL(string: urlString) else {
        return nil
    }
    
    return self.loadImage(from: url)
}

请记住,此代码会阻塞主线程,因此您应该在后台线程上运行它。例如:

DispatchQueue.global().async {
    let image = UIImage(fromFile: "http://xpto.com/image.png")
    
    // And then you should update UI on main thread.
    // If you have an UIImageView outlet you can update its image this way:
    DispatchQueue.main.async {
        imageView.image = image
        imageView.contentMode = .scaleAspectFit
    }
}
于 2020-08-26T16:20:32.523 回答
0

SWIFT 5.0 + 后台获取

private func fetchImage(_ photoURL: URL?) {

    guard let imageURL = photoURL else { return  }

    DispatchQueue.global(qos: .userInitiated).async {
        do{
            let imageData: Data = try Data(contentsOf: imageURL)

            DispatchQueue.main.async {
                let image = UIImage(data: imageData)
                self.userImageView.image = image
                self.userImageView.sizeToFit()
                self.tableView.reloadData()
            }
        }catch{
            print("Unable to load data: \(error)")
        }
    }
}
于 2019-06-06T14:26:00.393 回答
0

显示从 json 或 url 下载的图像的一个常见错误是队列问题。所有与 UI 相关的事情都需要在主队列中完成,所以如果你忘记了这一点,即使是完美的代码(上面的答案很好)有时也不会显示你的图像。要调用 mainQueue,请使用如下代码,并注意调用 main queue 可能需要在被调用的 imageDisplay 函数中单独完成:

dispatch_async(dispatch_get_main_queue(), ^{

    self.nameLabel.text = self.pokemon.name;

    [self displayImage];  //CALLS FUNCTION
    self.abilitiesTextView.text = @"loves SwiftUI";
});

- (void)displayImage {            

    NSString *imageURLString = [NSString stringWithFormat: self.pokemon.sprite];
    NSData *imageData = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString:imageURLString]];
    dispatch_async(dispatch_get_main_queue(), ^{
        self.spriteImageView.image = [UIImage  imageWithData: imageData];
    });

    // NOTE: important for newer versions of XCode/Obj-C...
    //[imageData release];   With ARC ("automated release..."), release method is forbidden, it's already done for you.
}
于 2019-07-27T20:27:01.213 回答
0

如果您愿意,甚至可以将其移至UIImage扩展程序:

extension UIImage {
    
    //NOTE: This is not thread safe, please run it on a background thread.
    convenience init?(fromFile filePath:String) {
        guard let url = URL(string: filePath) else {
            return nil
        }
        
        self.init(fromURL: url)
    }
    
    //NOTE: This is not thread safe, please run it on a background thread.
    convenience init?(fromURL url:URL) {
        let imageData: Data
        
        do {
            imageData = try Data(contentsOf: url)
        } catch {
            return nil
        }
        
        self.init(data: imageData)
    }
    
}
于 2020-08-26T17:39:08.600 回答