如何创建一个黑色的UIImage?(How to create a black UIImage?)

2019-08-23 01:54发布

我到处看了看四周,但我不能找到一个方法来做到这一点。 我需要建立一定的宽度和高度的黑色的UIImage(宽度和高度的变化,所以我不能只创建一个黑盒子,然后将其加载到一个UIImage)。 是否有某种方式做出的CGRect,然后将其转换为一个UIImage? 或者是有一些其他的方式做一个简单的黑盒子?

Answer 1:

根据你的情况,你很可能只是使用UIView与它backgroundColor设置为[UIColor blackColor] 另外,如果图像是实心的颜色,你并不需要这实际上是你想以显示它的尺寸的图像; 你可以扩展一个1x1像素的图像(例如,通过设置填补了必要的空间contentModeUIImageViewUIViewContentModeScaleToFill )。

话虽如此,它可能是有益的,看看如何实际产生这样的图像:

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();


Answer 2:

UIGraphicsBeginImageContextWithOptions(CGSizeMake(w,h), NO, 0);
UIBezierPath* p =
    [UIBezierPath bezierPathWithRect:CGRectMake(0,0,w,h)];
[[UIColor blackColor] setFill];
[p fill];
UIImage* im = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

现在, im是图像。

该代码来几乎没有变化,从我的书的这一部分: http://www.apeth.com/iOSBook/ch15.html#_graphics_contexts



Answer 3:

斯威夫特3:

func uiImage(from color:UIColor?, size:CGSize) -> UIImage? {

    UIGraphicsBeginImageContextWithOptions(size, true, 0)
    defer {
        UIGraphicsEndImageContext()
    }

    let context = UIGraphicsGetCurrentContext()
    color?.setFill()
    context?.fill(CGRect.init(x: 0, y: 0, width: size.width, height: size.height))
    return UIGraphicsGetImageFromCurrentImageContext()
}


Answer 4:

下面是创建由从一个CIImage创建CGImage创造它1920×1080黑UIImage的一个例子:

let frame = CGRect(origin: CGPoint(x: 0, y: 0), size: CGSize(width: 1920, height: 1080))
let cgImage = CIContext().createCGImage(CIImage(color: .black()), from: frame)!
let uiImage = UIImage(cgImage: cgImage)


文章来源: How to create a black UIImage?