iOS-swiftSwiftSwift开发

Kingfisher使用介绍

2018-06-15  本文已影响566人  CoderLWG

基本用法

imageView.kf.setImage(with: url)
// 带背景图片
let image = UIImage(named: "default_profile_icon")
imageView.kf.setImage(with: url, placeholder: image)

清除缓存

func clearCache() {
        KingfisherManager.shared.cache.clearMemoryCache()
        KingfisherManager.shared.cache.clearDiskCache()
    }

加载图片显示进度

 imageView.kf.setImage(with: url, placeholder: nil, options: [.transition(ImageTransition.fade(1))], progressBlock: { (receviveeSize, totalSize) in
            print("\(receviveeSize)/\(totalSize)")
        }) { (image, error, cacheType, imageURL) in
            print("Finished")
            // 加载完成的回调
            // image: Image? `nil` means failed
            // error: NSError? non-`nil` means failed
            // cacheType: CacheType
            //            .none - Just downloaded
            //            .memory - Got from memory cache
            //            .disk - Got from disk cache
            // imageUrl: URL of the image
        }

使用自定义key缓存,而不是用url

let resource = ImageResource(downloadURL: url!, cacheKey: "my_cache_key")
 imageView.kf.setImage(with: resource)

下载过程中 设置菊花样式

imageView.kf.indicatorType = .activity
imageView.kf.setImage(with: url)

使用自己的gif图片作为下载指示器
let path = Bundle.main.path(forResource: "loader", ofType: "gif")!
let data = try! Data(contentsOf: URL(fileURLWithPath: path)) imageView.kf.indicatorType = .image(imageData: data)
imageView.kf.setImage(with: url)

订制指示器view

struct MyIndicator: Indicator {
    let view: UIView = UIView()
    
    func startAnimatingView() {
        view.isHidden = false
    }
    func stopAnimatingView() {
        view.isHidden = true
    }
    
    init() {
        view.backgroundColor = .red
    }
}

let indicator = MyIndicator()
imageView.kf.indicatorType = .custom(indicator: indicator)

图片下载完成后,设置过度效果,淡入效果

imageView.kf.setImage(with: url, options: [.transition(.fade(0.2))])

在显示和缓存之前将下载的图像转换成圆角

let processor = RoundCornerImageProcessor(cornerRadius: 20)
imageView.kf.setImage(with: url, placeholder: nil, options: [.processor(processor)])

跳过缓存,强制重新下载

imageView.kf.setImage(with: url, options: [.forceRefresh])

只从缓存获取,不会下载

imageView.kf.setImage(with: url, options: [.onlyFromCache])

对Button添加图片

        let uiButton: UIButton = UIButton()
        uiButton.kf.setImage(with: url, for: .normal, placeholder: nil, options: nil, progressBlock: nil, completionHandler: nil)
        uiButton.kf.setBackgroundImage(with: url, for: .normal, placeholder: nil, options: nil, progressBlock: nil, completionHandler: nil)

Kingfisher 主要由两部分组成,ImageDownloader用于管理下载;ImageCache用于管理缓存,你可以单独使用其中一个

//使用ImageDownloader下载图片
        ImageDownloader.default.downloadImage(with: url!, options: [], progressBlock: nil) { (image, error, url, data) in
            print("Downloaded Image: \(image)")
        }
        
       // 使用ImageCache缓存图片
        let image: UIImage = UIImage(named: "xx.png")!
        ImageCache.default.store(image, forKey: "key_for_image")
        
        // Remove a cached image
        // From both memory and disk
        ImageCache.default.removeImage(forKey: "key_for_image")
        
        // Only from memory
        ImageCache.default.removeImage(forKey: "key_for_image",fromDisk: false)

设置缓存参数

// 设置磁盘缓存大小
        // Default value is 0, which means no limit.
        // 50 MB
        ImageCache.default.maxDiskCacheSize = 50 * 1024 * 1024
        
        // 获取缓存磁盘使用大小
        ImageCache.default.calculateDiskCacheSize { size in
            print("Used disk size by bytes: \(size)")
        }
        
        // 设置缓存过期时间
        // Default value is 60 * 60 * 24 * 7, which means 1 week.
        // 3 days
        ImageCache.default.maxCachePeriodInSecond = 60 * 60 * 24 * 3
        
        // 设置超时时间
        // Default value is 15.
        // 30 second
        ImageDownloader.default.downloadTimeout = 30.0

    // Clear cache manually
     // Clear memory cache right away.
     cache.clearMemoryCache()
     
     // Clear disk cache. This is an async operation.
     cache.clearDiskCache()
     
     // Clean expired or size exceeded disk cache. This is an async operation.
     cache.cleanExpiredDiskCache()

使用自定义的Downloader和cache代替默认的

        let downloader = ImageDownloader(name: "huge_image_downloader")
        downloader.downloadTimeout = 150.0
        let cache = ImageCache(name: "longer_cache")
        cache.maxDiskCacheSize = 60 * 60 * 24 * 30
        
        imageView.kf.setImage(with: url, options: [.downloader(downloader), .targetCache(cache)])
// 取消下载
        imageView.kf.cancelDownloadTask()

预先获取要显示的图片,需要显示时在直接添加

        let urls = ["http://example.com/image1.jpg", "http://example.com/image2.jpg"]
            .map { URL(string: $0)! }
        let prefetcher = ImagePrefetcher(urls: urls) {
            skippedResources, failedResources, completedResources in
            print("These resources are prefetched: \(completedResources)")
        }
        prefetcher.start()
        
        // Later when you need to display these images:
        imageView.kf.setImage(with: urls[0])
        anotherImageView.kf.setImage(with: urls[1])
上一篇下一篇

猜你喜欢

热点阅读