NPGradientImage - Swift 3的问题

时间:2016-10-25 11:05:13

标签: ios uilabel swift3 gradient

我使用https://github.com/nestorpopko/NPGradientImage-Swift为我的Label提供渐变效果。在将我的代码转换为Swift 3时,我遇到了UIImage + Gradient.swift文件的许多问题。任何人都可以帮我解决它吗?

1 个答案:

答案 0 :(得分:0)

最后我已经修复了swift3的问题,并且它的工作正常。只需使用以下代码替换UIImage + Gradient.swift

import UIKit

public extension UIImage
{
static func gradientImage(colors: [UIColor], locations: [CGFloat], size: CGSize, horizontal: Bool = false) -> UIImage {
    let endPoint = horizontal ? CGPoint(x: 1.0, y: 0.0) : CGPoint(x: 0.0, y: 1.0)
    return gradientImage(colors: colors, locations: locations, startPoint: CGPoint.zero, endPoint: endPoint, size: size)
}

static func gradientImage(colors: [UIColor], locations: [CGFloat], startPoint: CGPoint, endPoint: CGPoint, size: CGSize) -> UIImage
{
    UIGraphicsBeginImageContext(size)

    let context = UIGraphicsGetCurrentContext()
    UIGraphicsPushContext(context!);

    let components = colors.reduce([]) { (currentResult: [CGFloat], currentColor: UIColor) -> [CGFloat] in
        var result = currentResult

        let numberOfComponents = currentColor.cgColor.numberOfComponents
        let components = currentColor.cgColor.components


        if numberOfComponents == 2
        {
            result += ([(components?[0])!, (components?[0])!, (components?[0])!, (components?[1])!])
        }
        else
        {
            result += ([(components?[0])!, (components?[1])!, (components?[2])!, (components?[3])!])
        }

        return result
    }
    let gradient = CGGradient(colorSpace: CGColorSpaceCreateDeviceRGB(), colorComponents: components, locations: locations, count: colors.count);

    let transformedStartPoint = CGPoint(x: startPoint.x * size.width, y: startPoint.y * size.height)
    let transformedEndPoint = CGPoint(x: endPoint.x * size.width, y: endPoint.y * size.height)
    context?.drawLinearGradient(gradient!, start: transformedStartPoint, end: transformedEndPoint, options: []);
    UIGraphicsPopContext();
    let gradientImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    return gradientImage!
}
}