Vasyl Khmil
Vasyl Khmil

Reputation: 2557

Swift iOS add invisible border for UIImage

I'm writing my own keyboard, and i need buttons to be in distance of each other, so i need to add invisible border for my UIImage so it's my code

func imageWithBorderForImage(initalImage: UIImage, withWidth width: CGFloat, withHeight height: CGFloat) -> UIImage {
        UIGraphicsBeginImageContext(CGSizeMake(width , height));
        initalImage.drawInRect(CGRectMake(borderSize, borderSize, width - borderSize * 2, height - borderSize));
        let resultedImage = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
        return resultedImage
    }

This code adds border on top and left side as i expected but in bottom and right side it cuts my image. So where is a problem who knows?

Upvotes: 2

Views: 761

Answers (1)

Mick MacCallum
Mick MacCallum

Reputation: 130193

You're creating a context sized by your input parameters and then drawing the image inside it with the width and height cropped down by your border size. Instead, you should create your context sized to account for the gap you want, and then draw the image in its normal size offset by the border size.

func imageWithBorderForImage(initalImage: UIImage) -> UIImage {
    UIGraphicsBeginImageContext(CGSizeMake(initalImage.size.width + borderSize * 2.0, initalImage.size.height + borderSize * 2.0))

    initalImage.drawInRect(CGRectMake(borderSize, borderSize, initalImage.size.width, initalImage.size.height))
    let resultedImage = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()

    return resultedImage
}

Upvotes: 1

Related Questions