Skip to content

Commit

Permalink
Uses UIGraphicsImageRenderer in buildImagesWithTintColors(forControlS…
Browse files Browse the repository at this point in the history
…tateColors:fromControlStateImage:)
  • Loading branch information
philium committed Oct 17, 2018
1 parent feb87d8 commit 3de46f2
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 26 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -23,18 +23,15 @@ extension UIButton {
/// - Parameters:
/// - controlStateColors: A dictionary of control states (keys) and their cooresponding colors (values).
/// - controlState: The control state containing the mask image, default value is `.normal`.
///
func buildImagesWithTintColors(forControlStateColors controlStateColors: [UIControl.State: UIColor], fromControlStateImage controlState: UIControl.State = .normal) {

guard let normalImage = image(for: controlState) else {
print("[Tint Color Error] no default image for control state: \(controlState).")
return
}

for controlStateColor in controlStateColors {
if let controlStateImage = normalImage.renderImage(toMaskWithColor: controlStateColor.value) {
setImage(controlStateImage, for: controlStateColor.key)
}
controlStateColors.forEach { (state, color) in
setImage(normalImage.renderImage(toMaskWithColor: color), for: state)
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -65,30 +65,19 @@ extension UIImage {
return result
}

/// Make a copy of an image applying a color mask.
/// Makes a copy of an image applying a color mask.
///
/// - Parameter color: The color to apply to the color mask.
/// - Returns: A new `UIImage`.

func renderImage(toMaskWithColor color: UIColor) -> UIImage? {

UIGraphicsBeginImageContextWithOptions(size, false, scale)

guard let context = UIGraphicsGetCurrentContext() else {
UIGraphicsEndImageContext()
return nil
func renderImage(toMaskWithColor color: UIColor) -> UIImage {
let graphicsRenderer = UIGraphicsImageRenderer(size: size, format: .init(for: traitCollection))
return graphicsRenderer.image { (context) in
color.setFill()
context.cgContext.translateBy(x: 0, y: size.height)
context.cgContext.scaleBy(x: 1.0, y: -1.0)
let rect = CGRect(origin: .zero, size: size)
context.cgContext.clip(to: rect, mask: cgImage!)
context.fill(rect)
}

color.setFill()
context.translateBy(x: 0, y: size.height)
context.scaleBy(x: 1.0, y: -1.0)
context.clip(to: CGRect(x: 0, y: 0, width: size.width, height: size.height), mask: cgImage!)
context.fill(CGRect(x: 0, y: 0, width: size.width, height: size.height))

let coloredImg = UIGraphicsGetImageFromCurrentImageContext()

UIGraphicsEndImageContext()

return coloredImg
}
}

0 comments on commit 3de46f2

Please sign in to comment.