[英]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.