Sometimes you got a image from cache (memory or disk), but with the wrong scale, right now, I’ll share a method to resolve that.

1
2
3
4
5
6
7
8
9
// ... Get the cachedImage from somewhere
// Rescale the image
if (cachedImage.scale != [UIScreen mainScreen].scale) {
UIImage *scaledImage = [[UIImage alloc] initWithCGImage:cachedImage.CGImage scale:[UIScreen mainScreen].scale orientation:cachedImage.imageOrientation];
cachedImage = scaledImage;
}
return cachedImage;

Another case is the remote image from backend, they keep only @3 version, and the client’s UI layout want use the origin size of the image, then we can just rescale it.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
/**
* Backend remote image resource scale
**/
static const CGFloat ResourceScale = 3.0;
/**
* Make a rescaled image
**/
- (UIImage *)cm_rescaledImage {
if (CMFloatEqual(self.scale, ResourceScale)) {
return [self copy];
}
UIImage *scaledImage = [[UIImage alloc] initWithCGImage:self.CGImage
scale:ResourceScale
orientation:self.imageOrientation];
return scaledImage;
}

Pretty cool, isn’t it:D