本文介绍了在UIImage周围添加透明空间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我们有600X400的图像,我们希望最终得到1000X100的新图像,其中包含中心的初始图像和周围的透明空间。我怎样才能在代码中实现这一目标?

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?

推荐答案

你创建一个1000x1000的新图像上下文,在中间绘制你的旧图像,然后得到新的来自上下文的 UIImage

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), NO, 0.0);
CGContextRef context = UIGraphicsGetCurrentContext();
UIGraphicsPushContext(context);

// 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.
UIGraphicsPopContext();
UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

这篇关于在UIImage周围添加透明空间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-22 16:37