我是Swift的新手,我正在尝试使用CGGradient创建背景渐变,但是我收到以下错误。
无法将int类型的值转换为预期的参数类型CGGradientDrawingOptions
我不明白为什么我不应该在这里使用int。任何帮助将不胜感激。
override func viewDidLoad() {
super.viewDidLoad()
var currentContext = UIGraphicsGetCurrentContext()
CGContextSaveGState(currentContext);
var colorSpace = CGColorSpaceCreateDeviceRGB()
var topColor = UIColor(red: (57/255.0), green: (150/255.0), blue: (199/255.0), alpha: 1)
var startColorComponents = CGColorGetComponents(topColor.CGColor)
var middleColor = UIColor(red: (90/255.0), green: (60/255.0), blue: (117/255.0), alpha: 0.85)
var middleColorComponents = CGColorGetComponents(middleColor.CGColor)
var bottomColor = UIColor(red: (215/255.0), green: (109/255.0), blue: (109/255.0), alpha: 1)
var endColorComponents = CGColorGetComponents(bottomColor.CGColor)
var colorComponents
= [startColorComponents[0], startColorComponents[1], startColorComponents[2], startColorComponents[3],
middleColorComponents[0], middleColorComponents[1], middleColorComponents[2], middleColorComponents[3],
endColorComponents[0], endColorComponents[1], endColorComponents[2], endColorComponents[3]
]
var locations:[CGFloat] = [0.0, 0.35, 1.0]
var gradient = CGGradientCreateWithColorComponents(colorSpace,&colorComponents,&locations,3)
var startPoint = CGPointMake(-0.3, 0.1)
var endPoint = CGPointMake(0.2, 1.3)
CGContextDrawLinearGradient(currentContext,gradient,startPoint,endPoint, 0)
CGContextRestoreGState(currentContext);
}
答案 0 :(得分:0)
我假设你收到的错误是:
CGContextDrawLinearGradient(currentContext,gradient,startPoint,endPoint, 0)
这里的问题是你传递0(整数)的最后一个参数。
此例程的声明是:
public func CGContextDrawLinearGradient(c: CGContext?,
_ gradient: CGGradient?,
_ startPoint: CGPoint,
_ endPoint: CGPoint,
_ options: CGGradientDrawingOptions)
在Objective-C中,CGGradientDrawingOptions
类型是整数值的东西,其中0表示没有选项。在Swift中,绘图选项被声明为enum
类型的OptionSetType
。编译器抱怨,因为它期望这个枚举而不是整数。
在Swift中指定这些选项的方式看起来像一个数组,或包含枚举元素的集合。因此,如果您想要DrawsBeforeStartLocation
选项和DrawsAfterEndLocation
,您可以写:
CGContextDrawLinearGradient(someContext,
<other arguments here>
[.DrawsBeforeStartLocation, .DrawsAfterEndLocation])
在您的特定情况下,您不想要任何一个选项,所以只需传递一个空的选项集:
CGContextDrawLinearGradient(currentContext,gradient,startPoint,endPoint, [])