[英]How to load images using SDWebImage library
嗨,我正在使用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
加载图像?
步骤1:安装SDWebImage
首先,请确保您使用的是最新版本的SDWebImage
,并且是通过CocoaPods安装的(不建议手动链接该库)。
您的Podfile应该包含以下行:
pod 'SDWebImage', '~>3.7'
之后,关闭Xcode项目并在项目目录中运行pod install
。 安装后使用Xcode 工作区 。
步骤2:使用代码
首先,您已经导入了库
#import <SDWebImage/UIImageView+WebCache.h>
此时,请尝试清理并构建工作区。 如果一切顺利,则应正确构建项目。
然后,在您的函数中:
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
}
}];
完成。
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>
使用下面的代码行代替您的代码:
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"]];
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.