2

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?

1 Answer 1

1

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
}
Sign up to request clarification or add additional context in comments.

1 Comment

@user3417231 Sorry, the input sizes must not have been what I thought they were going to be. I've updated my code to make this more clear. I've tested this and it works perfectly.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.