public class func gradientColor(_ startPoint: CGPoint, endPoint: CGPoint, frame: CGRect, colors: [UIColor]) -> UIColor? {
// init a CAGradientLayer and set its frame
let gradientLayer = CAGradientLayer()
gradientLayer.frame = frame
// turn the array of UIColor's into an array of CGColor's
let cgColors = colors.map({$0.cgColor})
// set the colors of the gradient
gradientLayer.colors = cgColors
// set the start and end points of the gradient
gradientLayer.startPoint = startPoint
gradientLayer.endPoint = endPoint
// start an image context
UIGraphicsBeginImageContextWithOptions(gradientLayer.bounds.size, false, UIScreen.main.scale)
// draw the gradient layer in the context
gradientLayer.render(in: UIGraphicsGetCurrentContext()!)
// get the image of the gradient from the current image context
let gradientImage = UIGraphicsGetImageFromCurrentImageContext()
// end the context
UIGraphicsEndImageContext()
// return a new UIColor using the gradient image we made
return UIColor(patternImage: gradientImage!)
}
public class func radialGradientColor(_ frame: CGRect, colors: [UIColor]) -> UIColor? {
// start the image context
UIGraphicsBeginImageContextWithOptions(frame.size, false, UIScreen.main.scale)
// get an array of CGColor's from the UIColor's
let cgColors = colors.map({$0.cgColor})
// init a color space
let colorSpace = CGColorSpaceCreateDeviceRGB()
// get a CFArrayRef from our array of CGColor's
let arrayRef = cgColors as CFArray
// init the gradient
let gradient = CGGradient(colorsSpace: colorSpace, colors: arrayRef, locations: nil)
// make the center point in the center
let centrePoint = CGPoint(x: frame.size.width/2, y: frame.size.height/2)
// calculate the radius from the frame
let radius = max(frame.size.width, frame.size.height)/2
// draw the radial gradient
UIGraphicsGetCurrentContext()?.drawRadialGradient(gradient!,
startCenter: centrePoint,
startRadius: 0,
endCenter: centrePoint,
endRadius: radius,
options: .drawsAfterEndLocation)
// get a UIImage from the current context
let gradientImage = UIGraphicsGetImageFromCurrentImageContext()
// return a new UIColor from the radial gradient we just made
return UIColor(patternImage: gradientImage!)
}
颜色渐变
©著作权归作者所有,转载或内容合作请联系作者
- 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
- 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
- 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
推荐阅读更多精彩内容
- 前言 最近一直想写个app,可是不知道想些啥,今天给大家分享一下 渐变动起来的效果 效果 因为gif图比较大,所有...
- iOS UIlabel 的字体 字体颜色加入动画一开始考虑的是核心动画可惜并不支持, 最发现了 CATextLay...
- 现在好多app(喜马拉雅,新浪微博等)都有类似UIPageViewController的效果,实际开发中我们要进行...
- 需求 制作UGUI时,很多控件使用到了背景色,背景色效果包含:颜色的渐变和透明度的渐变。 因涉及到多种类似的背景图...