如何优雅的给按钮设置网络图片-更改按钮图片尺寸,使网络下载的图片适应按钮大小

为按钮设置网络图片, 可以使用SDWebImage第三方库提供的UIButton+WebCache.h 分类 提供的以下方法:
[btn sd_setImageWithURL:btnUrl forState:UIControlStateNormal];

#import "UIButton+WebCache.h"

- (void)viewDidLoad {
    [super viewDidLoad];
    
    NSURL *btnUrl = [NSURL URLWithString:@"http://cdn2.jianshu.io/assets/web/logo-58fd04f6f0de908401aa561cda6a0688.png"];
    UIButton *btn = [[UIButton alloc] initWithFrame:CGRectMake(60, 120, 180, 44)];
    [btn setBackgroundColor:[UIColor colorWithRed:0.95 green:0.95 blue:0.95 alpha:1]];
    [btn setTitle:@"进入" forState:UIControlStateNormal];
    [btn setTitleColor:[UIColor orangeColor] forState:UIControlStateNormal];
    [btn sd_setImageWithURL:btnUrl forState:UIControlStateNormal];
    [self.view addSubview:btn];
}
 

然而,使用了默认的网络图片大小, 显示起来却是这样的, 我尝试了各种按钮的属性设置, 都没有把这个妖孽改成合适大小. (包括尝试了更改按钮的imageEdgeInsets 属性, 也没成功.)


如何优雅的给按钮设置网络图片-更改按钮图片尺寸,使网络下载的图片适应按钮大小_第1张图片
默认网络图片大小是这样的.png

然后我想到了这样的方案: 下载下来的图片, 先调整图片的尺寸, 然后在去设置到按钮上, 同样, UIButton+WebCache.h 分类 提供的以下方法可以实现:

//这个方法提供了完成回调, 回调提供了下载下来的图片,这样我们就可以先更改这个图片的尺寸, 然后在设置给按钮使用.
[btn sd_setImageWithURL:btnUrl forState:UIControlStateNormal completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
        [btn setImage:image forState:UIControlStateNormal];
    }];
```
然后有了以下代码:
```
- (void)viewDidLoad {
    [super viewDidLoad];
    
    NSURL *btnUrl = [NSURL URLWithString:@"http://cdn2.jianshu.io/assets/web/logo-58fd04f6f0de908401aa561cda6a0688.png"];
    UIButton *btn = [[UIButton alloc] initWithFrame:CGRectMake(60, 120, 180, 44)];
    [btn setBackgroundColor:[UIColor colorWithRed:0.95 green:0.95 blue:0.95 alpha:1]];
    [btn setTitle:@"进入" forState:UIControlStateNormal];
    [btn setTitleColor:[UIColor orangeColor] forState:UIControlStateNormal];
    [btn sd_setImageWithURL:btnUrl forState:UIControlStateNormal completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
        image = [self imageByScalingToSize:CGSizeMake(80, 36) ForImage:image];
        [btn setImage:image forState:UIControlStateNormal];
    }];
    [self.view addSubview:btn];
}

- (UIImage *)imageByScalingToSize:(CGSize)targetSize ForImage:(UIImage *)image{
    //用作3倍率缩放, 保证图片不失真
    targetSize = CGSizeMake(targetSize.width*3, targetSize.height*3);
    
    UIImage *sourceImage = image;
    UIImage *newImage = nil;
    CGSize imageSize = sourceImage.size;
    CGFloat width = imageSize.width;
    CGFloat height = imageSize.height;
    CGFloat targetWidth = targetSize.width;
    CGFloat targetHeight = targetSize.height;
    CGFloat scaleFactor = 0.0;
    CGFloat scaledWidth = targetWidth;
    CGFloat scaledHeight = targetHeight;
    CGPoint thumbnailPoint = CGPointMake(0.0,0.0);
    if (CGSizeEqualToSize(imageSize, targetSize) == NO) {
        CGFloat widthFactor = targetWidth / width;
        CGFloat heightFactor = targetHeight / height;
        if (widthFactor < heightFactor)
            scaleFactor = widthFactor;
        else
            scaleFactor = heightFactor;
        scaledWidth  = width * scaleFactor;
        scaledHeight = height * scaleFactor;
        // center the image
        if (widthFactor < heightFactor) {
            
            thumbnailPoint.y = (targetHeight - scaledHeight) * 0.5;
        } else if (widthFactor > heightFactor) {
            thumbnailPoint.x = (targetWidth - scaledWidth) * 0.5;
        }
    }
    // this is actually the interesting part:
    UIGraphicsBeginImageContext(targetSize);
    CGRect thumbnailRect = CGRectZero;
    thumbnailRect.origin = thumbnailPoint;
    thumbnailRect.size.width  = scaledWidth;
    thumbnailRect.size.height = scaledHeight;
    [sourceImage drawInRect:thumbnailRect];
    newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    if(newImage == nil)
        NSLog(@"could not scale image");
    
    UIImage *image3Scale = [[UIImage alloc] initWithData:UIImagePNGRepresentation(newImage) scale:3.0];
    return image3Scale;
}
```

效果:

![设置图片的尺寸后再设置到按钮上.png](http://upload-images.jianshu.io/upload_images/1764130-82648e4cce363540.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)

你可能感兴趣的:(如何优雅的给按钮设置网络图片-更改按钮图片尺寸,使网络下载的图片适应按钮大小)