IOS基础图像处理

移动应用中图像处理对于用户体验来说至关重要,也是考验app性能、网络速度的重要指标。 在开发和使用app的过程中,ScrollView经常作为UIImageView的载体,在滑动过程中Image是否 流畅加载和显示是移动开发中最基本也是最常见的优化场景。下面就从一些最基本的方向来 总结一下Image的处理套路。

圆角

从很多网络资料上都可以看到对于UIImageView的圆角设置会导致离屏渲染,从而损伤性能, 那我们在开发中应该怎样去平衡性能损失和编码复杂度呢?一般情况下给UIImageView设置 圆角都是通过如下两行代码实现:

imageView.layer.cornerRadius = 5
imageView.layer.masksToBounds = true

这两行代码很简单,通过设置UIView的layer层来实现圆角,在页面图片圆角不多的情况下, 这就是最简单的方式,也不会带来多少性能损耗。

如果是页面图片圆角较多的话,如上操作会带来严重的性能问题,故不可取。此时可行的处理 方法就是直接截取图片实现:

- (UIImage *)imageWithSize:(CGSize)size cornerRadius:(CGFloat)cornerRadius {
    UIGraphicsBeginImageContextWithOptions(size, NO, [UIScreen mainScreen].scale);
    [[UIBezierPath bezierPathWithRoundedRect:CGRectMake(0, 0, size.width, size.height) cornerRadius:cornerRadius] addClip];
    [self drawInRect:CGRectMake(0, 0, size.width, size.height)];
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return image;
}

直接将截取好的图片填入UIImageView中,所以对于移动App中feed流这种需要好的体验的地方, 一般是采取的这种方式。当然对于普通的画图,我们也可以使用Core Graphics这样来实现:

+ (UIImage *)imageWithFillColor:(UIColor *)fillColor strokeColor:(UIColor *)strokeColor size:(CGSize)size lineWidth:(CGFloat)lineWidth cornerRadius:(CGFloat)radius {
    UIGraphicsBeginImageContextWithOptions(size, NO, [UIScreen mainScreen].scale);
    [fillColor setFill];
    [strokeColor setStroke];
    CGRect roundedRect = CGRectMake(lineWidth/2, lineWidth/2, size.width-lineWidth, size.height-lineWidth);
    UIBezierPath *path = [UIBezierPath bezierPathWithRoundedRect:roundedRect cornerRadius:radius];
    path.lineWidth = lineWidth;
    [path fill];
    [path stroke];
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return image;
}

当然我们可以重写一个UIView的drawRect方法来得到不同形状的UIView,但是调用drawRect 方法也会导致离屏渲染,实不可取。用上面的绘图方法绘出特定的图形,然后代替UIView才 是正确高效的实现方式。

主题色

每个app都有自己特有的tintColor,最明显的就是当我们选中一个TabBarItem的时候,图标 会变色,这种情况使用tintColor作为图标的选中色最合适不过了,那么我们怎样得到tintColor 背景的图片呢,可以为UIImage写一个扩展为UIImage+Tint.h,实现如下:

@implementation UIImage (Tint)
- (UIImage *) imageWithTintColor:(UIColor *)tintColor
{
    return [self imageWithTintColor:tintColor blendMode:kCGBlendModeDestinationIn];
}

- (UIImage *) imageWithGradientTintColor:(UIColor *)tintColor
{
    return [self imageWithTintColor:tintColor blendMode:kCGBlendModeOverlay];
}

- (UIImage *) imageWithTintColor:(UIColor *)tintColor blendMode:(CGBlendMode)blendMode
{
    //We want to keep alpha, set opaque to NO; Use 0.0f for scale to use the scale factor of the device’s main screen.
    if (tintColor) {
        UIGraphicsBeginImageContextWithOptions(self.size, NO, 0.0f);
        [tintColor setFill];
        CGRect bounds = CGRectMake(0, 0, self.size.width, self.size.height);
        UIRectFill(bounds);

        //Draw the tinted image in context
        [self drawInRect:bounds blendMode:blendMode alpha:1.0f];

        if (blendMode != kCGBlendModeDestinationIn) {
            [self drawInRect:bounds blendMode:kCGBlendModeDestinationIn alpha:1.0f];
        }

        UIImage *tintedImage = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();

        return tintedImage;
    }
    else {
        return self;
    }
}

@end

上面也是通过Core Graphics来为图片加载主题色的,至于代码中的blendMode,渲染模式对 透明度和渐变色产生影响,除非你对这个参数非常了解,否则请使用上面的方式。

透明度

设置一张图片或者UIView的透明度对于性能也会产生影响,设置图片透明度的正确姿势为:

- (UIImage *)imageByApplyingAlpha:(CGFloat) alpha {
    UIGraphicsBeginImageContextWithOptions(self.size, NO, 0.0f);

    CGContextRef ctx = UIGraphicsGetCurrentContext();
    CGRect area = CGRectMake(0, 0, self.size.width, self.size.height);

    CGContextScaleCTM(ctx, 1, -1);
    CGContextTranslateCTM(ctx, 0, -area.size.height);

    CGContextSetBlendMode(ctx, kCGBlendModeMultiply);

    CGContextSetAlpha(ctx, alpha);

    CGContextDrawImage(ctx, area, self.CGImage);

    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();

    UIGraphicsEndImageContext();

    return newImage;
}

大小

很多时候我们会去单纯地改变一张图片的大小,而且这种要求会很频繁,这里也是推荐使用 Core Graphics来改变一张图片的大小:

- (UIImage *)resizeImageWithMaxSize:(CGSize)maxSize {
    if (maxSize.width < FLT_EPSILON || maxSize.height < FLT_EPSILON) {
        return nil;
    }
    CGSize size = self.size;
    if (size.width < maxSize.width && size.height < maxSize.height) {
        return self;
    }

    CGFloat widthRatio = maxSize.width / size.width;
    CGFloat heightRatio = maxSize.height / size.height;
    CGFloat ratio = widthRatio < heightRatio ? widthRatio : heightRatio;
    CGSize finalSize = CGSizeMake(size.width * ratio, size.height * ratio);

    UIGraphicsBeginImageContext(finalSize);
    [self drawInRect:CGRectMake(0, 0, finalSize.width, finalSize.height)];
    UIImage *resizedImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return resizedImage;
}

缓存

当图片需要重复使用的时候,我们有必要对于图像进行缓存,这样能够消除CPU的重复图像 处理时间,在进行图像缓存的时候,使用最简单的NSMutableDictionary就行,缓存的Value 是UIImage,Key为图像的四个基本属性(name、UIImageTransformMode、size和cornerRadius) 当然,并不是这四个属性都是必须,不过一般情况下以name和size作为key。

+ (UIImage *)imageSVGNamed:(NSString *)name transformMode:(LNImageTransformMode)mode size:(CGSize)size cornerRadius:(CGFloat)cornerRadius cache:(BOOL)needCache {
    NSDictionary *cacheKey = @{@"name" : name, @"mode": @(mode), @"size": [NSValue valueWithCGSize:size], @"cornerRadius": @(cornerRadius)};
    UIImage *image = [[SVGImageCache sharedImageCache] cachedImageWithKey:cacheKey];
    if (image == nil) {
        image = [[UIImage svg2Image:name size:size] imageWithTransformMode:mode size:size cornerRadius:cornerRadius];
        if (image && needCache) {
            [[SVGImageCache sharedImageCache] addImageToCache:image forKey:cacheKey];
        }
    }

    return image;
}

格式

判断图像的格式很容易,读取图像二进制码的第一个字节就可以得到图片的格式。一般在开发中 常用的图片格式是Jpg、PNG、SVG和GIF。其中

Jpg格式适合于从网络上下载的、像素丰富、体积略大的图片(压缩空间比较大);
png适合于存储于客户端的小图标,但是需要为不同屏幕的图标大小做适配(*1、*2、*3);
SVG为矢量图,可以避开屏幕大小适配的问题,也是使用很广泛的图片格式;
GIF为动态图,其带有时间轴。


Previous     Next
zhing /
Published under (CC) BY-NC-SA in categories ios  tagged with ios