【iOS】加载SVG图片

一、导入 SVGKit 第三方库

# SVG 图片展示
pod 'SVGKit'

二、使用 SVGKit 库

  • 新建 UIImage+SVG 分类,二次封装SVGKit 库
/// UIImage+SVG.h
#import 

NS_ASSUME_NONNULL_BEGIN

@interface UIImage (SVG)
/**
 show svg image
 @param name svg name
 @return svg image
 */
+ (UIImage *)br_svgImageNamed:(NSString *)name;

/**
 show svg image
 @param name svg name
 @param size image size
 @return svg image
 */
+ (UIImage *)br_svgImageNamed:(NSString *)name size:(CGSize)size;

/**
 show svg image
 @param name       svg name
 @param size       image size
 @param tintColor  image color
 @return svg image
 */
+ (UIImage *)br_svgImageNamed:(NSString *)name size:(CGSize)size tintColor:(UIColor *)tintColor;

@end

NS_ASSUME_NONNULL_END
/// UIImage+SVG.m
#import "UIImage+SVG.h"
#import 

@implementation UIImage (SVG)

/**
 show svg image
 
 @param name svg name
 @return svg image
 */
+ (UIImage *)br_svgImageNamed:(NSString *)name {
    SVGKImage *svgImage = [SVGKImage imageNamed:name];
    return svgImage.UIImage;
}

/**
 show svg image
 
 @param name svg name
 @param size image size
 @return svg image
 */
+ (UIImage *)br_svgImageNamed:(NSString *)name size:(CGSize)size {
    SVGKImage *svgImage = [SVGKImage imageNamed:name];
    svgImage.size = size;
    return svgImage.UIImage;
}

/**
 show svg image
 
 @param name       svg name
 @param size       image size
 @param tintColor  image color
 @return svg image
 */
+ (UIImage *)br_svgImageNamed:(NSString *)name size:(CGSize)size tintColor:(UIColor *)tintColor {
    SVGKImage *svgImage = [SVGKImage imageNamed:name];
    svgImage.size = size;
    CGRect rect = CGRectMake(0, 0, svgImage.size.width, svgImage.size.height);
    CGImageAlphaInfo alphaInfo = CGImageGetAlphaInfo(svgImage.UIImage.CGImage);
    BOOL opaque = alphaInfo == kCGImageAlphaNoneSkipLast || alphaInfo == kCGImageAlphaNoneSkipFirst || alphaInfo == kCGImageAlphaNone;
    UIGraphicsBeginImageContextWithOptions(svgImage.size, opaque, svgImage.scale);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextTranslateCTM(context, 0, svgImage.size.height);
    CGContextScaleCTM(context, 1.0, -1.0);
    CGContextSetBlendMode(context, kCGBlendModeNormal);
    CGContextClipToMask(context, rect, svgImage.UIImage.CGImage);
    CGContextSetFillColorWithColor(context, tintColor.CGColor);
    CGContextFillRect(context, rect);
    UIImage *imageOut = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return imageOut;
}

@end
  • 加载SVG图片
UIImage *image1 = [UIImage br_svgImageNamed:@"icon_back.svg"];
UIImage *image2 = [UIImage br_svgImageNamed:@"icon_back.svg" size:CGSizeMake(12.0, 24.0)];
UIImage *image3 = [UIImage br_svgImageNamed:@"icon_back.svg" size:CGSizeMake(12.0, 24.0) tintColor:[UIColor whiteColor]];

你可能感兴趣的:(【iOS】加载SVG图片)