Ashish Kakkad
Ashish Kakkad

Reputation: 23882

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

I am learning swift language.

I am working on shapes. Can we add shadows to the shape?

I am creating rectangle using CGPathAndRect. How to add shadow to this?

Code to create rectangle:

  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)

  }

Upvotes: 1

Views: 835

Answers (2)

Ashish Kakkad
Ashish Kakkad

Reputation: 23882

Found an answer from 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)
}

Upvotes: 1

gabuh
gabuh

Reputation: 1166

Use Following Code :

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

after

UIColor.purpleColor().setFill()

Upvotes: 1

Related Questions