美文网首页
UILabel文字渐变色

UILabel文字渐变色

作者: 秋叶红90 | 来源:发表于2023-04-09 14:26 被阅读0次
    extension UIColor {
        static let gradientTextLink: UIColor = {
                let gradientLayer = CAGradientLayer.init(frame: CGRect.init(x: 0, y: 0, width: screenWidth, height: 16), colors: [rgba(104, 104, 167, 1),rgba(159, 32, 87, 1)], startPoint: CGPoint.init(x: 0.5, y: 0), endPoint: CGPoint.init(x: 0.5, y: 1))
            let linkColor = gradientLayer.outputColor() ?? UIColor.red
                return linkColor
            }()
    }
    extension CAGradientLayer {
        
        public convenience init(frame:CGRect,colors: [UIColor],locations:[NSNumber] = [0,1],startPoint:CGPoint = CGPoint.init(x: 0, y: 0.5),endPoint:CGPoint = CGPoint.init(x: 1, y: 0.5)) {
            //创建渐变层对象
            self.init()
            self.frame = frame
            //将存储的渐变色数组(UIColor类)转变为CAGradientLayer对象的colors数组,并设置该数组为CAGradientLayer对象的colors属性
            var gradientColors: [CGColor] = [];
            for item in colors {
                gradientColors.append(item.cgColor)
            }
            self.colors = gradientColors
            self.locations = locations
            self.startPoint =  startPoint
            self.endPoint =  endPoint
        }
    }
    
    extension CALayer {
        open func outputImage() -> UIImage? {
            UIGraphicsBeginImageContextWithOptions(self.frame.size, self.isOpaque, 0)
            guard let currentContext = UIGraphicsGetCurrentContext() else {
                return nil
            }
            self.render(in: currentContext )
            let ouputImage = UIGraphicsGetImageFromCurrentImageContext()
            UIGraphicsEndImageContext()
            return ouputImage
        }
        
        open func outputColor() -> UIColor? {
            guard let image = self.outputImage() else {
                return nil
            }
            return UIColor.init(patternImage: image)
        }
        
    }
    
    
    self.label.textColor = UIColor.gradientTextLink
    

    相关文章

      网友评论

          本文标题:UILabel文字渐变色

          本文链接:https://www.haomeiwen.com/subject/xkubddtx.html