Tassos Voulgaris Tassos Voulgaris - 8 months ago 59
iOS Question

Add transparent space around a UIImage

Lets say we have an image of 600X400 and we want to end up with an new image of 1000X100 which contains the initial image in the centre and transparent space around it. How can I achieve that in code?

enter image description here


You create a new image context that is 1000x1000, draw your old image in the middle, then get the new UIImage from the context.

// Setup a new context with the correct size
CGFloat width = 1000;
CGFloat height = 1000;
UIGraphicsBeginImageContextWithOptions(CGSizeMake(width, height), YES, 0.0);        
CGContextRef context = UIGraphicsGetCurrentContext();       

// Now we can draw anything we want into this new context.
CGPoint origin = CGPointMake((width - oldImage.size.width) / 2.0f,
                            (height - oldImage.size.height) / 2.0f);
[oldImage drawAtPoint:origin];

// Clean up and get the new image.
UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();