18

I want to change color of svg images. I am using following code, it hides the image and fill the whole image view with the color set.

 self.badmintonImgView.tintColor = [UIColor orangeColor];

I need to change the color of image. Please suggest

user
  • 221
  • 1
  • 2
  • 11

6 Answers6

50

If the SVG is in Assets.xcassets, you can tell Xcode to treat the image as an icon:

First, select your SVG image in the assets catalog

Then set the render mode to Template Image

אורי orihpt
  • 2,358
  • 2
  • 16
  • 41
27

Swift

To change the color of an SVG using Swift:

badmintonImgView.image = badmintonImgView.image?.withRenderingMode(.alwaysTemplate)
badmintonImgView.tintColor = UIColor.orange

enter image description here

Marcy
  • 4,611
  • 2
  • 34
  • 52
3

This worked for me:

UIImage * imageOrange = [[UIImage imageNamed:@"yourSVGImageName"] imageWithTintColor:UIColor.orangeColor];
UIImageView * yourImageView = [[UIImageView alloc] initWithImage: imageOrange];

remember add the image to the assets folder. I hope it helps you.

Pedro Trujillo
  • 1,559
  • 18
  • 19
0

Do as follow may be work for you.

SVGKImage *svgImage = [SVGKImage imageNamed:@"YOURIMAGENAME"];
SVGKLayeredImageView *svgImageView = [[SVGKLayeredImageView alloc] initWithSVGKImage:svgImage];
[capturedImageView addSubview:svgImageView];

CALayer* layer = svgImageView.layer;
for (CALayer *subLayer in layer.sublayers) {

    for (CALayer *subSubLayer in subLayer.sublayers) {


        for (CALayer *subSubSubLayer in subSubLayer.sublayers) {

            if( [subSubSubLayer isKindOfClass:[CAShapeLayer class]]){
                CAShapeLayer* shapeLayer = (CAShapeLayer*)subSubSubLayer;
                shapeLayer.fillColor = [UIColor BlackColor].CGColor;
            }
        }
    }
}
Hitesh Surani
  • 12,733
  • 6
  • 54
  • 65
0

Try this [self.badmintonImgView setTintColor:[UIColor redColor]];

Vishal Sonawane
  • 2,637
  • 2
  • 16
  • 21
0

For publishing iOS 14.0+, I used אורי orihpt's answer, but realized I had to do some additional steps that differ from other answers on here. When using the Image, I couldn't get tintColor to work, but foregroundColor worked for me. I don't know if you're targeting the whole image, but this solution targets only the SVG paths, instead of creating a background color as well on the image (similar to Marcy's output image).

Image("imageName")
  .foregroundColor(Color.red)
Eli017
  • 31
  • 7