2014-11-27 4 views
39

나는 투명한 흰색 PNG 파일입니다 제작 한 아이콘의 세트를 가지고 그들을 다른 색으로 착색합니다. 파란색, 회색 등.색상 변경 IOS

'클릭/태핑'으로 인해 회색으로 자동 변경됩니다.

enter image description here

은 무엇이를 달성하는 가장 좋은 방법이 될 것입니다 : 그래서 내가 탭 또는 정상 상태 중 하나를 원하는대로 해당 회색을 변경할 수 있습니다 같은데요?

답변

105

다음 코드는 버튼의 정상 상태에 대한 색조 색상을 설정합니다 :

let origImage = UIImage(named: "imageName"); 
let tintedImage = origImage?.imageWithRenderingMode(UIImageRenderingMode.AlwaysTemplate) 
btn.setImage(tintedImage, forState: .Normal) 
btn.tintColor = UIColor.redColor() 

당신은 당신의 필요에 따라 색조 색상을 변경할 수 있습니다 때 버튼의 상태가 변경됩니다.

편집 :이 (, 고전적인 이미지, 사진을 선택 ) 이미지의 변화 색조를 들어 Swift3

let origImage = UIImage(named: "imageName") 
let tintedImage = origImage?.withRenderingMode(.alwaysTemplate) 
btn.setImage(tintedImage, forState: .normal) 
btn.tintColor = .redColor 
+0

완벽한, 감사 메이트. – Galaxy

+0

완벽! 구원자 : D – Reshad

+0

원더풀! 그러나 원본 이미지 (색조가 없음)로 되돌리려면 어떻게해야합니까? – Marsman

13

iOS 7에는보기 (UIImageView 포함)에 tintColor라는 속성이 도입되었습니다. 그러나 UIImage에서 렌더링 유형을 설정해야 효과가 있습니다.

UIImage *originalImage = [UIImage imageNamed:@"image.png"]; 
UIImage *tintedImage = [originalImage imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate]; 
UIImageView *imageView = [[UIImageView alloc] initWithImage:tintedImage]; 

imageView.tintColor = [UIColor grayColor]; 
[self.view addSubview:imageView]; 

그러면 기본 상태로 남은 효과가 생성됩니다.

7

에 대한 업데이트 사용하는 :

예 이미지 : enter image description here enter image description here

스위프트 2

public extension UIImage { 
    /** 
    Tint, Colorize image with given tint color<br><br> 
    This is similar to Photoshop's "Color" layer blend mode<br><br> 
    This is perfect for non-greyscale source images, and images that have both highlights and shadows that should be preserved<br><br> 
    white will stay white and black will stay black as the lightness of the image is preserved<br><br> 

    <img src="http://yannickstephan.com/easyhelper/tint1.png" height="70" width="120"/> 

    **To** 

    <img src="http://yannickstephan.com/easyhelper/tint2.png" height="70" width="120"/> 

    - parameter tintColor: UIColor 

    - returns: UIImage 
    */ 
    public func tintPhoto(tintColor: UIColor) -> UIImage { 

     return modifiedImage { context, rect in 
      // draw black background - workaround to preserve color of partially transparent pixels 
      CGContextSetBlendMode(context, .Normal) 
      UIColor.blackColor().setFill() 
      CGContextFillRect(context, rect) 

      // draw original image 
      CGContextSetBlendMode(context, .Normal) 
      CGContextDrawImage(context, rect, self.CGImage) 

      // tint image (loosing alpha) - the luminosity of the original image is preserved 
      CGContextSetBlendMode(context, .Color) 
      tintColor.setFill() 
      CGContextFillRect(context, rect) 

      // mask by alpha values of original image 
      CGContextSetBlendMode(context, .DestinationIn) 
      CGContextDrawImage(context, rect, self.CGImage) 
     } 
    } 
    /** 
    Tint Picto to color 

    - parameter fillColor: UIColor 

    - returns: UIImage 
    */ 
    public func tintPicto(fillColor: UIColor) -> UIImage { 

     return modifiedImage { context, rect in 
      // draw tint color 
      CGContextSetBlendMode(context, .Normal) 
      fillColor.setFill() 
      CGContextFillRect(context, rect) 

      // mask by alpha values of original image 
      CGContextSetBlendMode(context, .DestinationIn) 
      CGContextDrawImage(context, rect, self.CGImage) 
     } 
    } 
    /** 
    Modified Image Context, apply modification on image 

    - parameter draw: (CGContext, CGRect) ->()) 

    - returns: UIImage 
    */ 
    private func modifiedImage(@noescape draw: (CGContext, CGRect) ->()) -> UIImage { 

     // using scale correctly preserves retina images 
     UIGraphicsBeginImageContextWithOptions(size, false, scale) 
     let context: CGContext! = UIGraphicsGetCurrentContext() 
     assert(context != nil) 

     // correctly rotate image 
     CGContextTranslateCTM(context, 0, size.height); 
     CGContextScaleCTM(context, 1.0, -1.0); 

     let rect = CGRectMake(0.0, 0.0, size.width, size.height) 

     draw(context, rect) 

     let image = UIGraphicsGetImageFromCurrentImageContext() 
     UIGraphicsEndImageContext() 
     return image 
    } 
} 

UPD

스위프트 3

extension UIImage { 

    /** 
    Tint, Colorize image with given tint color<br><br> 
    This is similar to Photoshop's "Color" layer blend mode<br><br> 
    This is perfect for non-greyscale source images, and images that have both highlights and shadows that should be preserved<br><br> 
    white will stay white and black will stay black as the lightness of the image is preserved<br><br> 

    <img src="http://yannickstephan.com/easyhelper/tint1.png" height="70" width="120"/> 

    **To** 

    <img src="http://yannickstephan.com/easyhelper/tint2.png" height="70" width="120"/> 

    - parameter tintColor: UIColor 

    - returns: UIImage 
    */ 
    func tintPhoto(_ tintColor: UIColor) -> UIImage { 

     return modifiedImage { context, rect in 
      // draw black background - workaround to preserve color of partially transparent pixels 
      context.setBlendMode(.normal) 
      UIColor.black.setFill() 
      context.fill(rect) 

      // draw original image 
      context.setBlendMode(.normal) 
      context.draw(cgImage!, in: rect) 

      // tint image (loosing alpha) - the luminosity of the original image is preserved 
      context.setBlendMode(.color) 
      tintColor.setFill() 
      context.fill(rect) 

      // mask by alpha values of original image 
      context.setBlendMode(.destinationIn) 
      context.draw(context.makeImage()!, in: rect) 
     } 
    } 

    /** 
    Tint Picto to color 

    - parameter fillColor: UIColor 

    - returns: UIImage 
    */ 
    func tintPicto(_ fillColor: UIColor) -> UIImage { 

     return modifiedImage { context, rect in 
      // draw tint color 
      context.setBlendMode(.normal) 
      fillColor.setFill() 
      context.fill(rect) 

      // mask by alpha values of original image 
      context.setBlendMode(.destinationIn) 
      context.draw(cgImage!, in: rect) 
     } 
    } 

    /** 
    Modified Image Context, apply modification on image 

    - parameter draw: (CGContext, CGRect) ->()) 

    - returns: UIImage 
    */ 
    fileprivate func modifiedImage(_ draw: (CGContext, CGRect) ->()) -> UIImage { 

     // using scale correctly preserves retina images 
     UIGraphicsBeginImageContextWithOptions(size, false, scale) 
     let context: CGContext! = UIGraphicsGetCurrentContext() 
     assert(context != nil) 

     // correctly rotate image 
     context.translateBy(x: 0, y: size.height) 
     context.scaleBy(x: 1.0, y: -1.0) 

     let rect = CGRect(x: 0.0, y: 0.0, width: size.width, height: size.height) 

     draw(context, rect) 

     let image = UIGraphicsGetImageFromCurrentImageContext() 
     UIGraphicsEndImageContext() 
     return image! 
    } 

} 
+0

이 방법을 사용하는 방법을 말해 줄 수 있습니까? – ashmi123

7

이 확장 사용할 수 있습니다

,316,114,844을
1

자산 카탈로그를 사용하는 경우 이미지 애셋 자체를 설정하여 템플릿 모드로 렌더링 할 수 있습니다. 그런 다음 인터페이스 빌더 (또는 코드)에서 단추의 tintColor를 설정할 수 있습니다.

0

단추의 이미지를 설정하려면 특성 관리자로 이동하여 단추 유형을 시스템으로 변경하십시오. 그런 다음 이미지를 설정하고 색조 색상을 변경하십시오. 이미지의 색상이 변경됩니다. 열리지 않으면 버튼 유형을 확인하십시오.

0

스위프트 4

let origImage = UIImage(named: "check") 
    let tintedImage = origImage?.withRenderingMode(.alwaysTemplate) 
    buttons[0].setImage(tintedImage, for: .normal) 
    buttons[0].tintColor = .red