AppKit在iOS中不可用,所以我一直在寻找替代品。
具体来说,我正在寻找替代方法:
- (NSColor *)interpolatedColorAtLocation: (CGFloat)location
我需要一种方法来定义渐变,并根据输入位置(float
)查找颜色值。
答案 0 :(得分:4)
如果你真的需要一个渐变对象(用于绘制渐变?),你可以使用CG级CGGradient“类”。
至于在渐变中的特定位置插入颜色,您需要知道的是两个周围的颜色(相对于您的给定位置)以及它们之间的插值(t
将是{之间的位置} {1}}相对于两种颜色,而不是整个渐变):
0.0..1.0
使用示例:
- (UIColor *)colorByInterpolatingWith:(UIColor *)color factor:(CGFloat)factor {
factor = MIN(MAX(t, 0.0), 1.0);
const CGFloat *startComponent = CGColorGetComponents(self.CGColor);
const CGFloat *endComponent = CGColorGetComponents(color.CGColor);
float startAlpha = CGColorGetAlpha(self.CGColor);
float endAlpha = CGColorGetAlpha(color.CGColor);
float r = startComponent[0] + (endComponent[0] - startComponent[0]) * factor;
float g = startComponent[1] + (endComponent[1] - startComponent[1]) * factor;
float b = startComponent[2] + (endComponent[2] - startComponent[2]) * factor;
float a = startAlpha + (endAlpha - startAlpha) * factor;
return [UIColor colorWithRed:r green:g blue:b alpha:a];
}
答案 1 :(得分:0)
这种颜色插值可以通过简单的线来实现:
let color = NSColor.green.interpolate(.blue, 0.5)
将此扩展程序添加到您的项目中:
extension NSColor{
/**
* Interpolates between two NSColors
* EXAMPLE: NSColor.green.interpolate(.blue, 0.5)
* NOTE: There is also a native alternative: NSColor.green.blended(withFraction: 0.5, of: .blue)
*/
func interpolate(_ to:NSColor,_ scalar:CGFloat)->NSColor{
func interpolate(_ start:CGFloat,_ end:CGFloat,_ scalar:CGFloat)->CGFloat{
return start + (end - start) * scalar
}
let fromRGBColor:NSColor = self.usingColorSpace(.genericRGB)!
let toRGBColor:NSColor = to.usingColorSpace(.genericRGB)!
let red:CGFloat = interpolate(fromRGBColor.redComponent, toRGBColor.redComponent,scalar)
let green:CGFloat = interpolate(fromRGBColor.greenComponent, toRGBColor.greenComponent,scalar)
let blue:CGFloat = interpolate(fromRGBColor.blueComponent, toRGBColor.blueComponent,scalar)
let alpha:CGFloat = interpolate(fromRGBColor.alphaComponent, toRGBColor.alphaComponent,scalar)
return NSColor.init(red: red, green: green, blue: blue, alpha: alpha)
}
}
通过此扩展和AnimLib
获得了波纹管动画