Search code examples
iosswiftcgrect

Swift - Add Color to CGrect


I'm currently Adding a rectangle to an image in case it's not squared "filling" the remaining space, making it square. The idea is that this is a cheap approach (in terms of time required to "force" an image to be squared).

As you can see in the image attached, the square I generate does not have a color, and this might confuse the user. This is why I'd like to add a color to the CGRect I'm generating. The problem is I've not found any way to do this. Any suggestions on how to give color to this square generated, would be greately appreciated.

enter image description here

enter image description here

The current code I have to do this is the following:

func forceSquaredImage(image: UIImage) -> UIImage{
    let maxDimension = max(image.size.height, image.size.width)

    var newImage : UIImage = image

    if(image.size.height > image.size.width){

        UIGraphicsBeginImageContextWithOptions(CGSize(width: maxDimension, height: maxDimension), false, 0.0);

        image.drawInRect(CGRectMake(image.size.height/2-image.size.width/2, 0, image.size.width, image.size.height))
        newImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()

    }else if(image.size.height < image.size.width){

        UIGraphicsBeginImageContextWithOptions(CGSize(width: maxDimension, height: maxDimension), false, 0.0);
        image.drawInRect(CGRectMake(0, image.size.width/2-image.size.height/2, image.size.width, image.size.height))
        newImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return newImage

    }

    return newImage

}

The desired result would be something like this (color red is just an example in this case):

enter image description here


Solution

  • Just fill with a background color before you draw the image:

    func forceSquaredImage(image: UIImage) -> UIImage{
        let maxDimension = max(image.size.height, image.size.width)
    
        var newImage : UIImage = image
        UIGraphicsBeginImageContextWithOptions(CGSize(width: maxDimension, height: maxDimension), false, 0.0);
        UIColor.redColor().set()
        UIBezierPath(rect: CGRect(x:0, y: 0, width:maxDimension, height:maxDimension)).fill()
        if(image.size.height > image.size.width) {
            image.drawInRect(CGRectMake(image.size.height/2-image.size.width/2, 0, image.size.width, image.size.height))
            }
        else if (image.size.height < image.size.width) {
            image.drawInRect(CGRectMake(0, image.size.width/2-image.size.height/2, image.size.width, image.size.height))
            }
            newImage = UIGraphicsGetImageFromCurrentImageContext()
            UIGraphicsEndImageContext()
    
            return newImage
    }