In ios, click the button to asynchronously load the image.
This article summarizes several methods for Asynchronously loading images in IOS, which are very simple and practical. For more information, see.
Compared with the original method:
The Code is as follows:
AsyncImageView. h:
# Import
@ Interface AsyncImageView: UIView
{
NSURLConnection * connection;
NSMutableData * data;
}
-(Void) loadImageFromURL :( NSURL *) url;
@ End
AsyncImageView. m:
# Import "AsyncImageView. h"
@ Implementation AsyncImageView
-(Id) initWithFrame :( CGRect) frame
{
Self = [super initWithFrame: frame];
If (self ){
// Initialization code
}
Returnself;
}
-(Void) loadImageFromURL :( NSURL *) url {
If (connection! = Nil) {[connection release];}
If (data! = Nil) {[data release];}
NSURLRequest * request = [NSURLRequest requestWithURL: url
CachePolicy: NSURLRequestUseProtocolCachePolicy
TimeoutInterval: 60.0];
Connection = [[NSURLConnection alloc]
InitWithRequest: request delegate: self];
}
-(Void) connection :( NSURLConnection *) theConnection
DidReceiveData :( NSData *) incrementalData {
If (data = nil ){
Data =
[[NSMutableData alloc] initWithCapacity: 2048];
}
[Data appendData: incrementalData];
}
-(Void) connectionDidFinishLoading :( NSURLConnection *) theConnection {
[Connection release];
Connection = nil;
If ([[self subviews] count]> 0 ){
[[Self subviews] objectAtIndex: 0] removeFromSuperview];
}
UIImageView * imageView = [[UIImageView alloc] initWithImage: [UIImage imageWithData: data] autorelease];
ImageView. contentMode = UIViewContentModeScaleAspectFit;
ImageView. autoresizingMask = (UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight );
[Self addSubview: imageView];
ImageView. frame = self. bounds;
[ImageView setNeedsLayout];
[Self setNeedsLayout];
[Data release];
Data = nil;
}
-(UIImage *) image {
UIImageView * iv = [[self subviews] objectAtIndex: 0];
Return [iv image];
}
-(Void) dealloc {
[Connection cancel];
[Connection release];
[Data release];
[Super dealloc];
}
@ End
Method 2:
Copy the Code as follows:
@ Interface UIButton (AsyncImage)
// Size by point
-(Void) setImageFromURL :( NSString *) urlString adjustToSize :( CGSize) size completion :( void (^) (void) completion logo :( UIImage *) logoImage;
@ End
@ Implementation UIButton (AsyncImage)
-(Void) setImageFromURL :( NSString *) urlString adjustToSize :( CGSize) size completion :( void (^) (void) completion logo :( UIImage *) logoImage
{
Dispatch_async (dispatch_get_global_queue (DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^ {
UIImage * image = nil;
NSURL * url = [NSURL URLWithString: urlString];
NSData * data = [NSData dataWithContentsOfURL: url];
Image = [UIImage imageWithData: data];
If (image ){
If (! CGSizeEqualToSize (size, CGSizeZero )){
Image = [UIImage imageWithCGImage: image. CGImage scale: [self scaleImage: image adjustToSize: size] orientation: image. imageOrientation];
}
If (logoImage ){
Image = [self addLogoImage: logoImage toImage: image];
}
Dispatch_async (dispatch_get_main_queue (), ^ {
[Self setImage: image forState: UIControlStateNormal];
Completion ();
});
}
Else {
NSLog (@ "async load error .");
}
});
}
// Scale the image to fit the button size
-(CGFloat) scaleImage :( UIImage *) image adjustToSize :( CGSize) size
{
CGFloat xScale = size. width/image. size. width;
CGFloat yScale = size. height/image. size. height;
Return 1.0/MIN (xScale, yScale );
}
-(UIImage *) addLogoImage :( UIImage *) logo toImage :( UIImage *) img
{
// Get image width and height
CGFloat scale = [UIScreen mainScreen]. scale;
Int w = scale * img. size. width;
Int h = scale * img. size. height;
Int logoWidth = logo. scale * logo. size. width;
Int logoHeight = logo. scale * logo. size. height;
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB ();
// Create a graphic context with CGBitmapContextCreate
CGContextRef context = CGBitmapContextCreate (NULL, w, h, 8, 4 * w, colorSpace, kCGImageAlphaPremultipliedFirst );
CGContextDrawImage (context, CGRectMake (0, 0, w, h), img. CGImage );
CGContextDrawImage (context, CGRectMake (w-logoWidth, 0, logoWidth, logoHeight), [logo CGImage]);
CGImageRef imageMasked = CGBitmapContextCreateImage (context );
CGContextRelease (context );
Cgcolorspacerelstrap (colorSpace );
Return [UIImage imageWithCGImage: imageMasked scale: scale orientation: img. imageOrientation];
}
@ End
Method 3:
?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
# Import <Foundation/Foundation. h> # Import "StringUtils. h" @ Interface ImageManager: NSObject { NSMutableDictionary * _ imageDict; NSMutableArray * _ imageArr; } @ Property (nonatomic, strong) NSString * httpUrl; @ Property (nonatomic, strong) NSMutableDictionary * imageDict; @ Property (nonatomic, assign) dispatch_queue_t networkQueue; + (ImageManager *) sharedInstance; -(Void) asyncImage :( NSString *) imageName imageView :( UIImageView *) imageView; // Jump -(Void) asyncImageInsert :( NSString *) imageName imageView :( UIImageView *) imageView insert :( BOOL) insert; // Do not download the previous data -(Void) asyncImageCleanOld :( NSString *) imageName imageView :( UIImageView *) imageView cleanOld :( BOOL) cleanOld; @ End |
Implementation file:
?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 |
// // ImageManager. m // Myb-ios // // Created by warrior gao on 13-6-5. // Copyright (c) 2013 51myb. All rights reserved. // # Import "ImageManager. h" @ Interface ImageManager () @ End @ Implementation ImageManager // Maximum number of cached images Static int counter = 0; @ Synthesize imageDict = _ imageDict; // Singleton + (ImageManager *) sharedInstance { Static id instance; Static dispatch_once_t onceToken; Dispatch_once (& onceToken, ^ { Instance = self. new; }); Return instance; } -(Id) init { If (self = [super init]) { Self. networkQueue = dispatch_queue_create ("com. warrior. network. image", nil ); _ ImageDict = [[NSMutableDictionary alloc] init]; _ ImageArr = [[NSMutableArray alloc] init]; } Return self; } -(NSString *) fileFullPath :( NSString *) fileName { NSString * cachePath = [NSSearchPathForDirectoriesInDomains (NSCachesDirectory, NSUserDomainMask, YES) objectAtIndex: 0]; NSString * fileFullPath = [NSString stringWithFormat: @ "% @/% @", cachePath, fileName]; Return fileFullPath; } // Do not download the previous data -(Void) asyncImageCleanOld :( NSString *) imageName imageView :( UIImageView *) imageView cleanOld :( BOOL) cleanOld { If (cleanOld) { [_ ImageArr removeAllObjects]; } [Self asyncImage: imageName imageView: imageView]; } // Queue insertion, priority -(Void) asyncImageInsert :( NSString *) imageName imageView :( UIImageView *) imageView insert :( BOOL) insert { If ([StringUtils isEmpty: imageName]) { Return; } NSData * data = [NSData dataWithContentsOfFile: [self fileFullPath: [imageName stringByReplacingOccurrencesOfString: @ "/" withString: @ "-"]; If (data = nil ){ [_ ImageDict setValue: imageView forKey: imageName]; If (insert) { [_ ImageArr insertObject: imageName atIndex: 0]; } Else { [_ ImageArr addObject: imageName]; } [Self cacheImage]; } Else { [ImageView setImage: [UIImage imageWithData: data]; } } // Normal, appended to the back -(Void) asyncImage :( NSString *) imageName imageView :( UIImageView *) imageView { [Self asyncImageInsert: imageName imageView: imageView insert: NO]; } // Asynchronously cache the image to a local machine, with a maximum of two threads -(Void) cacheImage { For (; counter <2 & _ imageArr. count> 0; counter ++) { NSString * imageName = nil; @ Synchronized (self ){ ImageName = [[_ imageArr objectAtIndex: 0] copy]; [_ ImageArr removeObjectAtIndex: 0]; } If (imageName = nil) continue; Dispatch_async (self. networkQueue, ^ { NSLog (@ "Starting: % @", imageName ); UIImage * avatarImage = nil; NSURL * url = [NSURL URLWithString: [NSString stringWithFormat: @ "% @", self. httpUrl, imageName]; NSData * responseData = [NSData dataWithContentsOfURL: url]; If (responseData. length> 0) { [ResponseData writeToFile: [self fileFullPath: [imageName stringByReplacingOccurrencesOfString: @ "/" withString: @ "-"] atomically: NO]; AvatarImage = [UIImage imageWithData: responseData]; NSLog (@ "Finishing: % @", imageName ); If (avatarImage ){ Dispatch_async (dispatch_get_main_queue (), ^ { UIImageView * imageView = [_ imageDict objectForKey: imageName]; If (imageView! = Nil & avatarImage! = Nil ){ [ImageView setImage: avatarImage]; } [_ ImageDict removeObjectForKey: imageName]; [ImageName release]; }); } } Counter --; [Self cacheImage]; }); } } @ End |
The above is all the content of this article. I hope you will like it.