How to prevent bold images with UIImageRenderingModeAlwaysTemplate

后端 未结 4 1910
野性不改
野性不改 2020-12-31 19:30

My application has a toolbar with image buttons on them (subclass of UIButton); when the user switches on the \"Bold text\" accessibility option, not only the text becomes b

4条回答
  •  春和景丽
    2020-12-31 19:41

    Swift solution:

    Set Default rendering mode on image (in asset catalog or from the code).

    Transform the image color with this function:

    extension UIImage {
        public func transform(withNewColor color: UIColor) -> UIImage
        {
            UIGraphicsBeginImageContextWithOptions(size, false, scale)
    
            let context = UIGraphicsGetCurrentContext()!
            context.translateBy(x: 0, y: size.height)
            context.scaleBy(x: 1.0, y: -1.0)
            context.setBlendMode(.normal)
    
            let rect = CGRect(x: 0, y: 0, width: size.width, height: size.height)
            context.clip(to: rect, mask: cgImage!)
    
            color.setFill()
            context.fill(rect)
    
            let newImage = UIGraphicsGetImageFromCurrentImageContext()!
            UIGraphicsEndImageContext()
            return newImage
        }
    
    }
    

    Set transformed image to button desired state:

    let redImage = image.transform(withNewColor: UIColor.red)
    btn?.setImage(redImage, for: .selected)
    

提交回复
热议问题