如何在 iOS 8 Swift 中为形状添加阴影?

How to add shadows to the shapes in iOS 8 Swift?

我正在学习 swift 语言。

我正在研究形状。我们可以给形状加上阴影吗?

我正在使用 CGPathAndRect 创建矩形。如何给这个添加阴影?

创建矩形的代码:

  func drawRectOnScreen(){

    let currentContext = UIGraphicsGetCurrentContext()

    let secondPath = CGPathCreateMutable()

    let secondRect = CGRect(x: 150, y: 250, width: 100, height: 100)

    CGPathAddRect(secondPath, nil, secondRect)

    CGContextAddPath(currentContext, secondPath)

    UIColor.purpleColor().setFill()

    CGContextDrawPath(currentContext, kCGPathFill)

  }

使用以下代码:

CGContextSetShadow(currentContext, CGSizeMake(-15, 20), 5)

之后
UIColor.purpleColor().setFill()

从 iOS 8 Swift Programming Cookbook

中找到答案
func drawRectAtTopOfScreen(){
     let currentContext = UIGraphicsGetCurrentContext()
     CGContextSaveGState(currentContext)
     let offset = CGSizeMake(10, 10)

     CGContextSetShadowWithColor(currentContext, offset, 20, UIColor.grayColor().CGColor)

     let path = CGPathCreateMutable()    
     let firstRect = CGRect(x: 55, y: 60, width: 150, height: 150)
     CGPathAddRect(path, nil, firstRect)
     CGContextAddPath(currentContext, path)
     UIColor(red: 0.20, green: 0.60, blue: 0.80, alpha: 1.0).setFill()

     CGContextDrawPath(currentContext, kCGPathFill)
     CGContextRestoreGState(currentContext)
}