//
//  GMGradualButton.swift
//  Gengmei
//
//  Created by Terminator on 2017/7/12.
//  Copyright © 2017年 更美互动信息科技有限公司. All rights reserved.
//

import UIKit

@objcMembers
class GMGradualButton: GMButton {
    
    // 如果gradualColor 和 disableColor同时有值，他们的count要是一样的
    var gradualColor = [UIColor]()
    var disableColor = [UIColor]()
    var intriSize = CGSize.zero
    
    override var intrinsicContentSize: CGSize {
        intriSize = super.intrinsicContentSize
        if gradualColor.count > 0 {
            setBackgroundImage(setGradualChangeColor(colors: gradualColor), for: .normal)
        }
        if disableColor.count > 0 {
            setBackgroundImage(setGradualChangeColor(colors: disableColor), for: .disabled)
        }
        return intriSize
    }
 
    private func setGradualChangeColor(colors: [UIColor]) -> UIImage? {
        
        let cfColors = colors.map { $0.cgColor }
        UIGraphicsBeginImageContextWithOptions(super.intrinsicContentSize, true, 0)
        let context = UIGraphicsGetCurrentContext()
        let colorSpace = CGColorSpaceCreateDeviceRGB()
        let gradient = CGGradient(colorsSpace: colorSpace, colors: cfColors as CFArray, locations: nil)
        let start = CGPoint(x: self.intriSize.width, y: 0)
        let end = CGPoint(x: 0, y: self.intriSize.height)
        context?.drawLinearGradient(gradient!, start: start, end: end, options: [.drawsBeforeStartLocation, .drawsAfterEndLocation])
        let image = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return image
    }

}
