当前位置: 首页 > 工具软件 > Kingfisher > 使用案例 >

Kingfisher 5.13~ UIImageView、UIButton类扩展加载 网络图片

东方志尚
2023-12-01

Kingfisher 5.13~ UIImageView、UIButton类扩展加载 网络图片
UIImage 图片压缩、沙盒存储


//MARK: - UIButton
extension UIButton {
    //UIButton kf网络 图片
    func setButton(url:String,placeholder:String){
        let placegholderImage = UIImage(named: placeholder)
        if url.count > 0 {
            let urlImage:ImageResource = ImageResource(downloadURL: URL(string: url)!)
            self.kf.setImage(with: urlImage, for: .normal, placeholder: placegholderImage)
        } else {
            self.setImage(placegholderImage, for: .normal)
        }
    }
}
//MARK: - UIImageView
extension UIImageView {
    //UIImageView 网络 图片
    func setImageView(url:String,placeholder:String){
        let placegholderImage = UIImage(named: placeholder)
        if url.count > 0 {
            let urlImage:ImageResource = ImageResource(downloadURL: URL(string: url)!)
            self.kf.setImage(with: urlImage, placeholder: placegholderImage)
        } else {
            self.image = placegholderImage
        }
    }
}
//MARK: - UIImage
extension UIImage {
    // 图片压缩
    static func imageCompress(image:UIImage) -> Data {
        var imgData = image.jpegData(compressionQuality: 1)
        if imgData!.count > 100 * 1024 {
            if imgData!.count > 1024 * 1024 { //1M以及以上
                imgData = image.jpegData(compressionQuality: 0.1)
            } else if imgData!.count > 512 * 1024 { //1M以及以上
                imgData = image.jpegData(compressionQuality: 0.3)
            }else if imgData!.count > 200 * 1024  {
                //0.25M-0.5M
                imgData = image.jpegData(compressionQuality: 0.5)
            } else {
                imgData = image.jpegData(compressionQuality: 0.8)
            }
        }
        return imgData!;
    }
    // 存储图片 到沙盒
    static func saveImage(image:UIImage,fileName:String) -> String {
        let path = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
        let filePath = path.appending("/" + fileName)
        let data:Data = image.jpegData(compressionQuality: 1)!
        FileManager.default.createFile(atPath: filePath, contents: data, attributes: nil)
        return filePath
    }
}

有问题或建议 请联系

 类似资料: