我不确定 Core Image 是适合这里工作的工具 - 你可能最好使用CGGradient
绘制图像的函数。
旁白:您所要求的在 CoreImage 中是可能的,但很麻烦。可以类比一下,作为 Photoshop 或其他常见图形软件的用户创建这些图像的操作...CoreImage 方式将如下所示:
- 为上面的渐变创建一个图层,用渐变填充整个画布,然后将图层转换到正确的位置和大小
- 为中间黑色部分创建一个图层,将整个画布填充为黑色,并将图层变换到合适的位置和大小
- 同上 #1,但对于底部渐变。
您可以通过组合生成器过滤器、变换过滤器和合成过滤器来实现此目的...
gradient -> transform -\
}-> composite -\
solid color -> transform -/ \
}-> composite
gradient -> transform ————————————————--/
但设置它会很丑陋。
同样,在 Photoshop 中,您可以使用选择工具和填充/渐变工具在单个图层中完全创建渐变-填充-渐变设计...这与使用 CoreGraphics 绘制单个图像类似。
那么,如何进行单通道 CG 绘制呢?像这样的东西...
func createImage(width: CGFloat, _ height: CGFloat) -> CGImage {
let gradientOffset: CGFloat = 10 // white at bottom and top before/after gradient
let gradientLength: CGFloat = 12 // height of gradient region
// create colors and gradient for drawing with
let space = CGColorSpaceCreateDeviceRGB()
let startColor = UIColor.whiteColor().CGColor
let endColor = UIColor.blackColor().CGColor
let colors: CFArray = [startColor, endColor]
let gradient = CGGradientCreateWithColors(space, colors, [0,1])
// start an image context
UIGraphicsBeginImageContext(CGSize(width: width, height: height))
defer { UIGraphicsEndImageContext() }
let context = UIGraphicsGetCurrentContext()
// fill the whole thing with white (that'll show through at the ends when done)
CGContextSetFillColorWithColor(context, startColor)
CGContextFillRect(context, CGRect(x: 0, y: 0, width: width, height: height))
// draw top gradient
CGContextDrawLinearGradient(context, gradient, CGPoint(x: 0, y: gradientOffset), CGPoint(x: 0, y: gradientOffset + gradientLength), [])
// fill solid black middle
CGContextSetFillColorWithColor(context, endColor)
CGContextFillRect(context, CGRect(x: 0, y: gradientOffset + gradientLength, width: width, height: height - 2 * gradientOffset - 2 * gradientLength))
// draw bottom gradient
CGContextDrawLinearGradient(context, gradient, CGPoint(x: 0, y: height - gradientOffset), CGPoint(x: 0, y: height - gradientOffset - gradientLength), [])
return CGBitmapContextCreateImage(context)!
}