iOS获取网络图片大小设置显示高度

Swfit获取网络图片高度设置显示控件的高度

    let imageSource = CGImageSourceCreateWithURL(URL(string: str)! as CFURL, nil)
                if let result = CGImageSourceCopyPropertiesAtIndex(imageSource!, 0, nil) as? Dictionary {
                    print("图片信息\(result)")
                    if let width = result["PixelWidth"] as? CGFloat, let height = result["PixelHeight"] as? CGFloat {
                        print("图片width:\(width),height:\(height)")
                      
                        let showHeight = height*((SCREEN_WIDTH-30)/width)
                        weakSelf.posterImageView.topY = SCREEN_HEIGHT/2-showHeight/2;
                        weakSelf.posterImageView.height = showHeight;
                        
                        weakSelf.personInfoView.topY = self.posterImageView.height - 76;
                        
                //        //H = H*(SCREEN_WIDTH/W) = 图片高*(屏幕宽/图片宽)
                //        CGFloat showHeight = imgHeight * layoutWidth/imgWidth;
                    }
                }
do {
                    let data:Data = try Data.init(contentsOf: NSURL.init(string:str)! as URL)
                    let image:UIImage = UIImage.init(data: data)!
                    var height = image.size.height
                    var width = image.size.width
                    let scale = height / width
                    width = SCREEN_WIDTH
                    height = SCREEN_WIDTH * scale
                    weakSelf.posterImageView.frame = CGRect(x:16, y:(SCREEN_HEIGHT - height)/2.0, width:width, height:height)

                } catch {

                }

OC获取方式
导入#import

NSMutableString *imageURL = [NSMutableString stringWithFormat:@"https://res-qn.xxx.cn/pyqwak_minpro/posters/qingchen/person-holding-white-ceramic-mug-1239403.jpg?imageMogr2/thumbnail/200x/format/jpg/quality/80"];

CGImageSourceRef source = CGImageSourceCreateWithURL((CFURLRef)[NSURL URLWithString:imageURL], NULL);
NSDictionary* imageHeader = (__bridge NSDictionary*) CGImageSourceCopyPropertiesAtIndex(source, 0, NULL);
NSLog(@"Image header info %@",imageHeader);
CGFloat pixelHeight = [[imageHeader objectForKey:@"PixelHeight"] floatValue];
CGFloat pixelWidth  = [[imageHeader objectForKey:@"PixelWidth"] floatValue];
CGSize size = CGSizeMake(pixelWidth, pixelHeight);

通过 XHWebImageAutoSize来实现(推荐)

/**
     *  参数1:图片URL
     *  参数2:imageView 宽度
     *  参数3:预估高度,(此高度仅在图片尚未加载出来前起作用,不影响真实高度)
     */
 CGFloat imageHeight = [XHWebImageAutoSize imageHeightForURL:[NSURL URLWithString:@"www.baidu.com"] layoutWidth:width estimateHeight:256];

你可能感兴趣的:(iOS获取网络图片大小设置显示高度)