//
//  UIImage.swift
//  thinkgeek
//
//  Created by Jeremy Wiebe on 2015-09-02.
//  Copyright (c) 2015 Mobify. All rights reserved.
//

import Foundation
import UIKit

extension UIImage {
    @objc func withTint(_ color: UIColor) -> UIImage {
        // Uses CoreGraphics to draw into a new graphics context.
        // The current image (self) is used as a mask to fill
        // the graphics context with the requested color (ie. we
        // re-draw the image using the specified color) while
        // retaining alpha information.

        // Passing `0.0` as the last argument causes drawing to
        // occur in the screen scale.
        UIGraphicsBeginImageContextWithOptions(self.size, false, 0.0)

        let drawRect = CGRect(origin: CGPoint.zero, size: self.size)
        draw(in: drawRect)

        color.set()
        UIRectFillUsingBlendMode(drawRect, .sourceAtop)
        let tintedImage = UIGraphicsGetImageFromCurrentImageContext()

        UIGraphicsEndImageContext()

        // We don't expect this to ever be nil but in case something changes,
        // we have a unit test verifying that this force unwrap does't explode.
        return tintedImage!
    }
}
