Swift 判断image size 和GIF和长图的区别

不必废话,直接干货。

获取方法 1:图片尺寸size

/// 图片尺寸size
```
func getImageSize(_ url: String?) -> CGSize {
    
    guard let urlStr = url else {
        
        return CGSize.zero
    }
    
    let tempUrl = URL(string: urlStr)
    
    let imageSourceRef = CGImageSourceCreateWithURL(tempUrl! as CFURL, nil)
    
    var width: CGFloat = 0
    
    var height: CGFloat = 0
    
    if let imageSRef = imageSourceRef {
        
        let imageProperties = CGImageSourceCopyPropertiesAtIndex(imageSRef, 0, nil)
        
        if let imageP = imageProperties {
            
            let imageDict = imageP as Dictionary
            
            width = imageDict[kCGImagePropertyPixelWidth] as! CGFloat
            
            height = imageDict[kCGImagePropertyPixelHeight] as! CGFloat
            
        }
    }
    
    return CGSize(width: width, height: height)
    
}

方法二:推荐用这个,因为可以异步获取,不卡顿 并处理相关 GIF和长图的判断(长图目前我这边是根据高是屏幕的2倍,可能不是最佳方案,可以根据自己需求做处理)

  guard let url = URL(string:l) else {
                return
            }
            let resource = ImageResource(downloadURL: url)
            self.imgView.kf.setImage(with: resource, options: [.transition(ImageTransition.fade(1))], completionHandler:  { image, error, type, url in
                if let i = image{
                    let size = i.size
                    
                    if let uri = url {
                        
                        if  uri.pathExtension == "gif" {
                            
                            NSLog("----这是GIF")
                            self.gifLb.font = UIFont.systemFont(ofSize: 14, weight: .semibold)
                            self.gifLb.textColor = UIColor.white
                            self.gifLb.backgroundColor = UIColor.rgba(230, 230, 230, 0.3)
                            self.gifLb.textAlignment = .center
                            self.gifLb.text = "GIF"
                        }
                        
                        if  size.height > ( YJScreen.height  * 2 ) && uri.pathExtension != "gif"{
                    
                            NSLog("----这是长图")
                            self.gifLb.font = UIFont.systemFont(ofSize: 14, weight: .semibold)
                            self.gifLb.textColor = UIColor.white
                            self.gifLb.backgroundColor = UIColor.rgba(230, 230, 230, 0.3)
                            self.gifLb.textAlignment = .center
                            self.gifLb.text = "长图"
                        }
                        
                    }
                }
            })

你可能感兴趣的:(Swift 判断image size 和GIF和长图的区别)