aryaxt
aryaxt

Reputation: 77596

Swift - Core graphics and setting background color?

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?

public extension UIImage {

    public func imageCenteredInParentWithSize(size: CGSize, backgroundColor: UIColor = UIColor.clearColor()) -> 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
    }

}

EDIT:

Here is the working version

public func imageCenteredInParentWithSize(size: CGSize, backgroundColor: UIColor = UIColor.clearColor()) -> 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
}

Upvotes: 5

Views: 10272

Answers (2)

stefandouganhyde
stefandouganhyde

Reputation: 4544

The line backgroundColor.setFill() just sets the fill color of the current context, it doesn't actually do the filling. One way of performing the fill is to call CGContextFillRect(context, CGRect(x: 0, y: 0, width: size.width, height: size.height)) after setting the fill color.

Additionally, you should probably pass the scale of the UIImage as the scale parameter in UIGraphicsBeginImageContextWithOptions rather than 0.0. Also, you don't need the push- and pop-context lines at all - you're already working the in current context.

Upvotes: 9

cbiggin
cbiggin

Reputation: 2142

Looks to me like you're setting your background color to "Clear" (as in no color) which means it will show whatever color is set on the background view... which is almost certainly black.

You need to set the default to "UIColor.whiteColor()".

Upvotes: 0

Related Questions