I recently wrote another IOS skin swap APP, which uses the dynamic loading of images. This scenario is generally divided into two types: APP built-in resources (in the APP package ), another method is to download resources (resources under Documents). In this case, we will encounter a problem where all the objects uploaded by Documents are xxxx.png without the @ 2x suffix. If I use the common method as follows: UIImage imageNamed: In this method, we do not need to worry about whether the current screen resolution is a high-split screen. This function will help us find different images for different screens, if we need to consider whether to solve this problem by ourselves, we do not need to deal with the answer as long as we use the correct method.
The following method will help us solve the problem we want:
Image = [UIImage imageWithContentsOfFile: strPath];
The general implementation method is as follows:
NSMutableArray * reps = [NSMutableArray arrayWithCapacity: 2];
CGImageSourceRef src1X = CreateCGImageSourceWithFile (imagePath );
CGImageSourceRef src2X = CreateCGImageSourceWithFile ([[imagePath stringByDeletingPathExtension] stringByAppendingString: @ "@ 2x"] stringByAppendingPathExtension: [imagePath pathExtension]);
If (src1X ){
UIImageRep * rep = [[UIImageRep alloc] initWithCGImageSource: src1X imageIndex: 0 scale: 1];
If (rep) [reps addObject: rep];
[Rep release];
CFRelease (src1X );
}
If (src2X ){
UIImageRep * rep = [[UIImageRep alloc] initWithCGImageSource: src2X imageIndex: 0 scale: 2];
If (rep) [reps addObject: rep];
[Rep release];
CFRelease (src2X );
}
Return ([reps count]> 0 )? Reps: nil;
However, if we convert the implementation method, for example, we can use NSData to load images.
NSData * imageData = [NSData dataWithContentsOfFile: imageFullPath];
Image = [UIImage imageWithData: imageData];
However, NSData does not perform any special processing on the image path. If the input path does not contain @ 2x, only a single image can be returned.
Therefore, you need to determine whether @ 2x is needed by yourself.
The image loading path can be completely solved. Compared with imageNamed, there is only one cache problem. You can feel the difference when you repeat the image multiple times, which is also a good solution, I used NSCache to implement its own cache. NSCache will also automatically help us release the cache when the memory is insufficient. Each time we retrieve the image, we will first cache it and will not read the file again, the success is simple.
// Obtain the image from the cache
-(UIImage *) getCacheImageByPath :( NSString *) path
{
If (_ cache = nil ){
_ Cache = [[NSCache alloc] init];
Return nil;
}
UIImage * image = (UIImage *) [_ cache objectForKey: path];
Return image;
}
This is not teaching, but my personal notes. If you think it is not easy to handle, you are welcome to provide a better solution.
QQ407300101