image scale和size的关系与SDScaledImageForKey

之前总是理解不了scale和size的关系,只知道图片一般给三张b.png, b@2x.png, b@3x.png。对应不同的手机,iphone6以下的retain屏都是@2x, plus用的是@3x。

如:120*120的图片

    1x的size(120*120)

        2x的size(60*60)

        3x的size(40*40)

其实size才是开发中参考的数值,我们定义imageView的size最大不能超过image的size,否则拉伸模糊!


------------------------------------------------------------------------------------------------------------

今天看了SDWebImage里的SDScaledImageForKey函数:
inline UIImage *SDScaledImageForKey(NSString *key, UIImage *image) {
    if (!image) {
        return nil;
    }
    
    if ([image.images count] > 0) {
        NSMutableArray *scaledImages = [NSMutableArray array];

        for (UIImage *tempImage in image.images) {
            [scaledImages addObject:SDScaledImageForKey(key, tempImage)];
        }

        return [UIImage animatedImageWithImages:scaledImages duration:image.duration];
    }
    else {
        if ([[UIScreen mainScreen] respondsToSelector:@selector(scale)]) {
            CGFloat scale = 1.0;
            if (key.length >= 8) {
                // Search @2x. at the end of the string, before a 3 to 4 extension length (only if key len is 8 or more @2x. + 4 len ext)
                NSRange range = [key rangeOfString:@"@2x." options:0 range:NSMakeRange(key.length - 8, 5)];
                if (range.location != NSNotFound) {
                    scale = 2.0;
                }
            }

            UIImage *scaledImage = [[UIImage alloc] initWithCGImage:image.CGImage scale:scale orientation:image.imageOrientation];
            image = scaledImage;
        }
        return image;
    }
}
这段代码有什么作用呢?
imageName可以根据文件的名字@2x @3x 自动生成对应的image.但是从网络下载的图片则不会,它的scale就是1,很显示是错误的!所以要把image的scale重新设置成正确的!
为了验证网络图片scale为1,我写了如下代码:
NSURLRequest *request = [[NSURLRequest alloc] initWithURL:[NSURL URLWithString:@"http://127.0.0.1/php/php/b@2x.png"]];
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue new] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
        UIImage *image = [UIImage imageWithData:data];//scale:1, size:(width = 322, height = 467)
        UIImage *image2 = [UIImage imageNamed:@"b@2x.png"];//scale:2 size(width = 161, height = 233.5)
        
    }];
通过网络获取和imageNamed加载同一张图片b@2x.png,得出结论是正确的!


  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值