更改按钮中png的颜色-ios

更改按钮中png的颜色-ios,ios,swift,Ios,Swift,我已经创建了一组透明的白色PNG图标: 我想做的是把它们染成其他颜色。例如蓝色、灰色等 我注意到“点击/点击”会自动变为灰色。因此,我假设我可以用水龙头或其正常状态将灰色更改为我喜欢的任何颜色: 实现这一点的最佳方法是什么?iOS 7为视图(包括UIImageView)引入了一个名为tintColor的属性。但是,您还需要在UIImage上设置渲染类型,以使其生效 UIImage *originalImage = [UIImage imageNamed:@"image.png"]; UIIm

我已经创建了一组透明的白色PNG图标:

我想做的是把它们染成其他颜色。例如蓝色、灰色等

我注意到“点击/点击”会自动变为灰色。因此,我假设我可以用水龙头或其正常状态将灰色更改为我喜欢的任何颜色:


实现这一点的最佳方法是什么?

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];

这将在默认状态下产生您想要的效果

以下代码将设置按钮正常状态的色调:

对于Swift 4及更新版本:

let origImage = UIImage(named: "imageName")
let tintedImage = origImage?.withRenderingMode(.alwaysTemplate)
btn.setImage(tintedImage, for: .normal)
btn.tintColor = .red
当按钮状态发生变化时,您可以根据需要更改色调颜色


旧版本 对于Swift 3:

let origImage = UIImage(named: "imageName")
let tintedImage = origImage?.withRenderingMode(.alwaysTemplate)
btn.setImage(tintedImage, forState: .normal)
btn.tintColor = .redColor
对于Swift 2: 请参阅修订历史。

有关图像色调的更改(拾取经典图像照片),请使用以下选项:

示例图像:

Swift 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
    }
}
公共扩展UIImage{
/**
着色,使用给定的着色颜色为图像着色

这类似于Photoshop的“颜色”图层混合模式

这非常适用于非灰度源图像,以及应保留高光和阴影的图像

白色将保持为白色,黑色将保持为黑色,因为图像的亮度得以保持

**到** -参数tintColor:UIColor -返回:UIImage */ 公共func tintPhoto(tintColor:UIColor)->UIImage{ 返回modifiedImage{context,rect in //绘制黑色背景-保留部分透明像素颜色的解决方法 CGContextSetBlendMode(上下文、.Normal) UIColor.blackColor().setFill() CGContextFillRect(上下文,rect) //绘制原始图像 CGContextSetBlendMode(上下文、.Normal) CGContextDrawImage(上下文、rect、self.CGImage) //着色图像(丢失alpha)-保留原始图像的亮度 CGContextSetBlendMode(上下文,.Color) tintColor.setFill() CGContextFillRect(上下文,rect) //通过原始图像的alpha值进行遮罩 CGContextSetBlendMode(上下文,.DestinationIn) CGContextDrawImage(上下文、rect、self.CGImage) } } /** 着色 -参数fillColor:UIColor -返回:UIImage */ 公共func tintPicto(fillColor:UIColor)->UIImage{ 返回modifiedImage{context,rect in //画淡色 CGContextSetBlendMode(上下文、.Normal) fillColor.setFill() CGContextFillRect(上下文,rect) //通过原始图像的alpha值进行遮罩 CGContextSetBlendMode(上下文,.DestinationIn) CGContextDrawImage(上下文、rect、self.CGImage) } } /** 修改图像上下文,对图像应用修改 -参数绘制:(CGContext,CGRect)->()) -返回:UIImage */ private func modifiedImage(@noescape draw:(CGContext,CGRect)->())->UIImage{ //使用scale可以正确地保存视网膜图像 UIGraphicsBeginImageContextWithOptions(大小、错误、比例) let context:CGContext!=UIGraphicsGetCurrentContext() 断言(上下文!=nil) //正确旋转图像 CGContextTranslateCm(上下文,0,大小.高度); CGContextScaleCTM(上下文,1.0,-1.0); 设rect=CGRectMake(0.0,0.0,size.width,size.height) 绘制(上下文,矩形) 让image=UIGraphicsGetImageFromCurrentImageContext() UIGraphicsSendImageContext() 返回图像 } }
UPD

Swift 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!
    }

}
扩展UIImage{ /** 着色,使用给定的着色颜色为图像着色

这类似于Photoshop的“颜色”图层混合模式

这非常适用于非灰度源图像,以及应保留高光和阴影的图像

白色将保持为白色,黑色将保持为黑色,因为图像的亮度得以保持

**到** -参数tintColor:UIColor -返回:UIImage */ func tintPhoto(tintColor:UIColor)->UIImage{ 返回modifiedImage{context,rect in //绘制黑色背景-保留部分透明像素颜色的解决方法 context.setBlendMode(.normal) UIColor.black.setFill() context.fill(rect) //绘制原始图像 context.setBlendMode(.normal) context.draw(cgImage!,in:rect) //着色图像(丢失alpha)-保留原始图像的亮度 context.setBlendMode(.color) tintColor.setFill() context.fill(rect) //通过原始图像的alpha值进行遮罩 context.setBlendMode(.destinationIn) context.draw(context.makeImage()!,in:rect) } } /** 着色 -参数fillColor:UIColor -返回:UIImage */ func tintPicto(fillColor:UIColor)->UIImage{ 返回modifiedImage{context,rect in //画淡色 context.setBlendMode(.normal) fillColor.setFill() context.fill(rect) //通过原始图像的alpha值进行遮罩 context.setBlendMode(.destinationIn) context.draw(cgImage!,in:rect) } } /** 修改图像上下文,对图像应用修改 -参数绘制:(CGContext,CGRect)->()) -返回:UIImage */ fileprivate func modifiedImage(_
    let origImage = UIImage(named: "check")
    let tintedImage = origImage?.withRenderingMode(.alwaysTemplate)
    buttons[0].setImage(tintedImage, for: .normal)
    buttons[0].tintColor = .red
let img = UIImage.init(named: "buttonName")?.withRenderingMode(UIImageRenderingMode.alwaysTemplate)
            btn.setImage(img, for: .normal)
            btn.tintColor = .gray
extension UIButton{

    func setImageTintColor(_ color: UIColor) {
        let tintedImage = self.imageView?.image?.withRenderingMode(.alwaysTemplate)
        self.setImage(tintedImage, for: .normal)
        self.tintColor = color
    }

}
button.setImage(UIImage(named: "image_name"), for: .normal) // You can set image direct from Storyboard
button.setImageTintColor(UIColor.white)
yourButton.tintColor = .gray