UIImageView add SVG format picture

Posted by vixtay on Thu, 02 Jan 2020 14:09:16 +0100

pod import

pod 'SVGKit'

pod 'CocoaLumberjack'

 

Create a category for UIImage

.h file

/**

@param name svg name  xxx.svg

@param size image size

@return svg image

*/

+(UIImage *)svgImgNamed:(NSString *)name size:(CGSize)size;

.m

#import "UIImage+SVGTool.h"

#import <SVGKImage.h>

@implementation UIImage (SVGTool)

/**
 @param name svg name-->xxx.svg
 @param size image size
 @return svg image
 */
+(UIImage *)svgImgNamed:(NSString *)name size:(CGSize)size{
    SVGKImage *svgImg = [SVGKImage imageNamed:name];
    svgImg.size = size;
    return svgImg.UIImage;
}

@end

 

Quote

    UIImage *image = [UIImage svgImgNamed:@"icon_light.svg" size:CGSizeMake(80,80)];

It's too limited to write in this way. If you need a picture of this kind with other colors, it's too much trouble to write another one. It's a waste of resources. Why not present it in another way

.h

/**

@param name svg name  -->xxx.svg

@param size image size

@param color image color

@return svg image

*/

+ (UIImage *)svgImageNamed:(NSString *)name size:(CGSize)size imageColor:(UIColor *)color;

.m

/**

@param name svg name -->xxx.svg

@param size image size

@param color image color

@return svg image

*/

+ (UIImage *)svgImageNamed:(NSString *)name size:(CGSize)size imageColor:(UIColor *)color {

    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, color.CGColor);

    CGContextFillRect(context, rect);

    UIImage *imageOut = UIGraphicsGetImageFromCurrentImageContext();

    UIGraphicsEndImageContext();

    return imageOut;

}

Quote

 UIImage *image = [UIImage svgImageNamed:@"icon_light.svg" size:CGSizeMake(80,80) imageColor:[UIColor greenColor]];

In this way, is it more convenient to add a color directly to the color you want

matters needing attention:

1. Calling the above code to run on the real machine may cause errors in SVGKit

For example:

Find the + (float) pixelsPerInchForCurrentDevice {} method in the SVGLength.m file to add a phone model, such as iPhone 6, iPhone 7

2. There are also some macros that report errors and directly comment (DDLogCWarn, etc.)