问题描述
我已经四处张望,但我找不到办法。我需要创建一个黑色的UIImage一定的宽度和高度(宽度和高度的变化,所以我不能只创建一个黑盒子,然后将其加载到UIImage)。有没有办法做一个CGRect,然后将其转换为UIImage?
I've looked around everywhere, but I can't find a way to do this. I need to create a black UIImage of a certain width and height (The width and height change, so I can't just create a black box and then load it into a UIImage). Is there some way to make a CGRect and then convert it to a UIImage? Or is there some other way to make a simple black box?
推荐答案
根据你的情况,你可能只是使用一个将
backgroundColor
设置为 [UIColor blackColor]
。此外,如果图像是纯色的,您不需要一个实际上是您要显示它的尺寸的图像;您可以只缩放1x1像素图像以填充必要的空间(例如,通过将 UIImageView
的 contentMode
设置为 UIViewContentModeScaleToFill
)。
Depending on your situation, you could probably just use a UIView
with its backgroundColor
set to [UIColor blackColor]
. Also, if the image is solidly-colored, you don't need an image that's actually the dimensions you want to display it at; you can just scale a 1x1 pixel image to fill the necessary space (e.g., by setting the contentMode
of a UIImageView
to UIViewContentModeScaleToFill
).
尽管如此,看看如何实际生成这样的图像可能是有益的: / p>
Having said that, it may be instructive to see how to actually generate such an image:
CGSize imageSize = CGSizeMake(64, 64);
UIColor *fillColor = [UIColor blackColor];
UIGraphicsBeginImageContextWithOptions(imageSize, YES, 0);
CGContextRef context = UIGraphicsGetCurrentContext();
[fillColor setFill];
CGContextFillRect(context, CGRectMake(0, 0, imageSize.width, imageSize.height));
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
这篇关于如何创建一个黑色的UIImage?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!