您好我正在使用SDWebImage
加载图片确定没问题
这里我从服务中获取图片,我想调整这些图片的大小,我想使用SDWebImage
加载它们
为此我写了下面的代码
Obj.imageYH---> this is imageURL
NSData *imageData = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString:Obj.imageYH]];
UIImage *actualImage = [UIImage imageWithData:imageData];
UIGraphicsBeginImageContext(CGSizeMake(150, 150));
[actualImage drawInRect:CGRectMake(0,0,150, 150)];
UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
NSData *smallData = UIImagePNGRepresentation(newImage);
NSString *Finalstring = [[NSString alloc] initWithData:smallData encoding:NSUTF8StringEncoding] ;
[Mainimage sd_setImageWithURL:[NSURL URLWithString: Finalstring] placeholderImage:[UIImage imageNamed:@"collectionViewIcon.png"]];
但是在上面的代码中,我在Finalstring
中获得了空值。如何调整大小以及如何使用SDWebImage
加载图像?
答案 0 :(得分:2)
第1步:安装SDWebImage
首先,请确保您使用的是最新版本的SDWebImage
,并通过CocoaPods安装(不建议手动链接库)。
您的Podfile应包含以下行:
pod 'SDWebImage', '~>3.7'
之后,关闭Xcode项目并在项目目录中运行pod install
。安装后使用Xcode 工作区。
第2步:使用代码
首先,您已导入库
#import <SDWebImage/UIImageView+WebCache.h>
此时,请尝试清洁&amp;构建工作区。如果一切顺利,项目应该没有错误地构建。
然后,在你的函数中:
SDWebImageManager *manager = [SDWebImageManager sharedManager];
[manager downloadImageWithURL:Obj.imageYH
options:0
progress:^(NSInteger receivedSize, NSInteger expectedSize) {
// progression tracking code, optional.
// You can set the progress block to nil
}
completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished, NSURL *imageURL) {
if (image) {
// Resize your image here, then set it to UIImageView
Mainimage.image = [UIImage imageWithData:UIImagePNGRepresentation(image) scale:0.5f];
// resize to 0.5x, function available since iOS 6
}
}];
进行。
答案 1 :(得分:1)
SDWebImageManager *manager = [SDWebImageManager sharedManager];
[manager downloadWithURL:url delegate:self options:0 success:^(UIImage
*image) {
cell.profilePicture.image = [self imageByScalingAndCroppingForSize:CGSizeMake(cell.profilePicture.frame.size.width,
cell.profilePicture.frame.size.height) image:image]; } failure:nil];
不要忘记包含
#import <SDWebImage/UIImageView+WebCache.h>
@interface YourViewController : UIViewController <SDWebImageManagerDelegate>
答案 2 :(得分:1)
使用以下代码行代替您的代码:
UIImage *actualImage = [UIImage imageWithData:imageData];
UIGraphicsBeginImageContext(CGSizeMake(150, 150));
[actualImage drawInRect:CGRectMake(0,0,150, 150)];
UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
NSData *smallData = UIImagePNGRepresentation(newImage);
[smallData writeToFile:Finalstring atomically:YES];// Finalstring is file path of resize image
[Mainimage sd_setImageWithURL:[NSURL URLWithString: Finalstring] placeholderImage:[UIImage imageNamed:@"collectionViewIcon.png"]];