//
//  UIView+Extension.swift
//  Example
//
//  Created by QuintGao on 2022/3/21.
//  Copyright © 2022 QuintGao. All rights reserved.
//

import Foundation
import QuartzCore

extension UIView {
    
    //添加银河渐变色 //从左到右
    func addYinHeGradualLayer() {
        let gradientLayer = CAGradientLayer()
        gradientLayer.colors = UIColor.arrBrandGradaterColors.map(\.cgColor)
        gradientLayer.locations = [0, 1.0]
        gradientLayer.startPoint = CGPoint(x: 0.12, y: 0.25)
        gradientLayer.endPoint = CGPoint(x: 0.38, y: 0.25)
        gradientLayer.frame = bounds
        gradientLayer.zPosition = -1
        layer.addSublayer(gradientLayer)
    }
    
    func image(with colors: [Any]) -> UIImage? {
        addYinHeGradualLayer()
        return convertToImage()
    }
    
    
    
    func convertToImage() -> UIImage? {
        let size = self.bounds.size
        if size.width <= 0 || size.height <= 0 { return nil }
        UIGraphicsBeginImageContextWithOptions(size, false, UIScreen.main.scale)
        guard let context = UIGraphicsGetCurrentContext() else { return nil }
        self.layer.render(in: context)
        let image = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return image
    }
    
    // 画虚线
    func drawBorderDottedLine(width:CGFloat,length:CGFloat,space:CGFloat,cornerRadius:CGFloat,color:UIColor) {
          self.layer.cornerRadius = cornerRadius
          let borderLayer =  CAShapeLayer()
          borderLayer.bounds = self.bounds
          
          borderLayer.position = CGPoint(x: self.bounds.midX, y: self.bounds.midY);
          borderLayer.path = UIBezierPath(roundedRect: borderLayer.bounds, cornerRadius: cornerRadius).cgPath
          borderLayer.lineWidth = width
          //虚线边框---小边框的长度
          borderLayer.lineDashPattern = [length,space]  as [NSNumber]?
          //前边是虚线的长度，后边是虚线之间空隙的长度
          borderLayer.lineDashPhase = 0.1
          //实线边框
          
          borderLayer.fillColor = UIColor.clear.cgColor
          borderLayer.strokeColor = color.cgColor
          self.layer.addSublayer(borderLayer)
    }
    
    // 任意切圆角 eg:UIRectCorner(rawValue: (UIRectCorner.topRight.rawValue) | (UIRectCorner.bottomRight.rawValue)
    public func createCorner(_ cornerRadii:CGSize,_ roundingCorners:UIRectCorner) {

        let path = UIBezierPath(roundedRect:bounds,byRoundingCorners: roundingCorners,cornerRadii:cornerRadii);
        let layer = CAShapeLayer();
        layer.frame = bounds;
        layer.path = path.cgPath;
        self.layer.mask = layer;

    }

}
