我试图找出如何创建一个不是完美圆形的椭圆渐变。例如美式橄榄球/橄榄球/眼睛形状而不是圆形。
目前我已经创建了一个如下所示的CALayer子类,它创建了一个圆圈。我怎样才能将它变成椭圆形(如上所述)?
class CircleGradientLayer: CALayer {
var startRadius: CGFloat?
var startCenter: CGPoint?
var endCenter: CGPoint?
var endRadius: CGFloat?
var locations: [CGFloat]?
var colors: [UIColor]?
override func drawInContext(ctx: CGContext) {
super.drawInContext(ctx)
if let colors = self.colors, let locations = self.locations, let startRadius = self.startRadius, let startCenter = self.startCenter, let endCenter = self.endCenter, let endRadius = self.endRadius {
var colorSpace: CGColorSpaceRef?
var components = [CGFloat]()
for i in 0 ..< colors.count {
let colorRef = colors[i].CGColor
let colorComponents = CGColorGetComponents(colorRef)
let numComponents = CGColorGetNumberOfComponents(colorRef)
if colorSpace == nil {
colorSpace = CGColorGetColorSpace(colorRef)
}
for j in 0 ..< numComponents {
let component = colorComponents[j]
components.append(component)
}
}
if let colorSpace = colorSpace {
let gradient = CGGradientCreateWithColorComponents(colorSpace, components, locations, locations.count)
CGContextDrawRadialGradient(ctx, gradient, startCenter, startRadius, endCenter, endRadius, CGGradientDrawingOptions.DrawsAfterEndLocation)
}
}
}
}
答案 0 :(得分:3)
这样做的一种方法是通过将某个因子缩放X来设置图层的变换。例如:
layer.transform = CATransform3DMakeScale(1.5, 1.0)
不确定这是否是最佳解决方案,但它应该有效!