title: Swift - Core graphics and setting background color?
body: <p>I created this method that generates and image out of an original one but adds padding to the new image according to a given size. Everything works fine except the background color of the image is always black although I set white as fill color. Any idea how to fix this?</p>
  
  <pre><code>public extension UIImage {
  
      public func imageCenteredInParentWithSize(size: CGSize, backgroundColor: UIColor = UIColor.clearColor()) -&gt; UIImage {
          UIGraphicsBeginImageContextWithOptions(CGSizeMake(size.width, size.height), true, 0.0)
          let context = UIGraphicsGetCurrentContext()
          UIGraphicsPushContext(context);
  
          let origin = CGPointMake(
              (size.width - self.size.width) / 2.0,
              (size.height - self.size.height) / 2.0
          )
  
          backgroundColor.setFill()
          drawAtPoint(origin)
  
          UIGraphicsPopContext()
          let newImage = UIGraphicsGetImageFromCurrentImageContext()
          UIGraphicsEndImageContext()
  
          return newImage
      }
  
  }
  </code></pre>
  
  <p><strong>EDIT:</strong></p>
  
  <p>Here is the working version</p>
  
  <pre><code>public func imageCenteredInParentWithSize(size: CGSize, backgroundColor: UIColor = UIColor.clearColor()) -&gt; UIImage {
      UIGraphicsBeginImageContextWithOptions(CGSizeMake(size.width, size.height), true, UIScreen.mainScreen().scale)
      let context = UIGraphicsGetCurrentContext()
  
      let origin = CGPointMake(
          (size.width - self.size.width) / 2.0,
          (size.height - self.size.height) / 2.0
      )
  
      backgroundColor.setFill()
      CGContextFillRect(context,  CGRectMake(0, 0, size.width, size.height))
      drawAtPoint(origin)
  
      let newImage = UIGraphicsGetImageFromCurrentImageContext()
      UIGraphicsEndImageContext()
  
      return newImage
  }
  </code></pre>