Jos*_*iah 20 cocoa-touch objective-c uiimage
这不是你可能认为的开始.我知道如何使用UIImage,但我现在需要知道如何使用以下方法创建"空白"UIImage:
CGRect screenRect = [self.view bounds];
那么,那些维度.无论如何,我想知道如何创建一个UIImage,其颜色全白.这里没有实际图像.
这甚至可能吗?我确信它是,但也许我错了.
这需要是一个"白色"图像.不是空白的.:)
Ben*_*ayo 36
您需要使用CoreGraphics,如下所示.
CGSize size = CGSizeMake(desiredWidth, desiredHeight);
UIGraphicsBeginImageContextWithOptions(size, YES, 0);
[[UIColor whiteColor] setFill];
UIRectFill(CGRectMake(0, 0, size.width, size.height));
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
Run Code Online (Sandbox Code Playgroud)
代码创建一个新的CoreGraphics图像上下文,其中选项作为参数传递; 尺寸,不透明度和比例.通过传递0比例,iOS会自动为当前设备选择适当的值.
然后,将上下文填充颜色设置为[UIColor whiteColor].然后,通过使用UIRectFill()并传递填充画布的矩形,画布立即实际上填充了该颜色.
甲UIImage然后当前上下文的创建,并且上下文被关闭.因此,图像变量包含UIImage所需大小,填充白色.
Swift版本:
extension UIImage {
static func emptyImage(with size: CGSize) -> UIImage? {
UIGraphicsBeginImageContext(size)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image
}
}
Run Code Online (Sandbox Code Playgroud)
小智 5
如果你只想绘制一个空图像,你可以使用 UIKit UIImageBeginImageContextWithOptions: 方法。
UIGraphicsBeginImageContext(CGSizeMake(width, height));
CGContextAddRect(UIGraphicsGetCurrentContext(), CGRectMake(0, 0, width, height)); // this may not be necessary
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
Run Code Online (Sandbox Code Playgroud)
上面的代码假设您绘制的图像大小为宽 x 高。它将矩形添加到图形上下文中,但可能不是必需的。自己试试吧。这是要走的路。:)
或者,如果您想创建当前视图的快照,您可以键入如下代码;
UIGraphicsBeginImageContext(CGSizeMake(self.view.size.width, self.view.size.height));
[self.view.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
Run Code Online (Sandbox Code Playgroud)
如果您使用图层,请不要忘记包含 Quartz 库。
| 归档时间: |
|
| 查看次数: |
17183 次 |
| 最近记录: |