这就是我得到的:
这是我尝试过的代码,但它只绘制没有阴影的渐变圆。
有人可以帮助或解释如何在一个上下文中使用 CGContextSetShadowWithColor
和 CGContextDrawLinearGradient
使其工作吗?
override func drawRect(rect: CGRect) {
// context
let context = UIGraphicsGetCurrentContext()
// value
let centerX = rect.width / 2.0
let centerY = rect.height / 2.0
let radius = rect.width * 0.33
// colors
let shadowColor = UIColor(white: 0.0, alpha: 0.8)
// gradient
CGContextSaveGState(context)
CGContextSetShadowWithColor(
context,
CGSizeMake(0, 0),
10.0,
shadowColor.CGColor
)
let ellipseRect = CGRectMake(centerX - radius / 2, centerY - radius / 2, radius, radius)
CGContextAddEllipseInRect(context, ellipseRect)
CGContextClip(context)
let colorSpace = CGColorSpaceCreateDeviceRGB()
let colors: [CGFloat] = [
// rgba
44.0 / 255.0, 61.0 / 255.0, 96.0 / 255.0, 1.0,
09.0 / 255.0, 18.0 / 255.0, 30.0 / 255.0, 1.0
]
let gradient: CGGradientRef = CGGradientCreateWithColorComponents(colorSpace, colors, nil, 2)!
let gradientStart: CGPoint = CGPointMake(centerX, centerY - radius / 2);
let gradientEnd: CGPoint = CGPointMake(centerX, centerY + radius / 2);
CGContextDrawLinearGradient(context, gradient, gradientStart, gradientEnd, .DrawsBeforeStartLocation)
CGContextRestoreGState(context)
}
最佳答案
解决方法是先绘制带有阴影的黑色圆圈,然后在该圆圈上绘制渐变。
这是代码:
override func drawRect(rect: CGRect) {
if let context = UIGraphicsGetCurrentContext() {
// values
let centerX = rect.width / 2.0
let centerY = rect.height / 2.0
let radius = rect.width * 0.33
// colors
let shadowColor = UIColor(white: 0.0, alpha: 0.8)
// circle in center with shadow
let ellipseRect = CGRectMake(centerX - radius / 2, centerY - radius / 2, radius, radius)
CGContextSaveGState(context)
CGContextSetShadowWithColor(
context,
CGSizeMake(0, 0),
10.0,
shadowColor.CGColor
)
CGContextFillEllipseInRect(context, ellipseRect)
CGContextRestoreGState(context)
// gradient
let colors: [CGFloat] = [
// rgba
44.0 / 255.0, 61.0 / 255.0, 96.0 / 255.0, 1.0,
09.0 / 255.0, 18.0 / 255.0, 30.0 / 255.0, 1.0
]
CGContextSaveGState(context)
let colorSpace = CGColorSpaceCreateDeviceRGB()
let gradient: CGGradientRef = CGGradientCreateWithColorComponents(colorSpace, colors, nil, 2)!
CGContextAddEllipseInRect(context, ellipseRect)
CGContextClip(context)
let gradientStart: CGPoint = CGPointMake(centerX, centerY - radius / 2);
let gradientEnd: CGPoint = CGPointMake(centerX, centerY + radius / 2);
CGContextDrawLinearGradient(context, gradient, gradientStart, gradientEnd, .DrawsBeforeStartLocation)
CGContextRestoreGState(context)
}
}
关于ios - 绘制带阴影的渐变圆,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39330064/