如何创build一个黑色的UIImage?
我环顾四周,但我找不到办法做到这一点。 我需要创build一个特定宽度和高度的黑色UIImage(宽度和高度的变化,所以我不能只是创build一个黑盒子,然后加载到UIImage)。 有没有办法做一个CGRect,然后将其转换为UIImage? 或者有其他的方法来制作一个简单的黑盒子吗?
根据你的情况,你可能可以使用[UIColor blackColor]
backgroundColor
[UIColor blackColor]
设置为[UIColor blackColor]
。 此外,如果图像颜色鲜明,则不需要实际上是要显示的图像的图像; 您可以缩放1×1像素的图像以填充必要的空间(例如,通过将UIImageView
的contentMode
设置为UIViewContentModeScaleToFill
)。
话虽如此,看看如何实际生成这样的图像可能是有益的:
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();
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
Swift 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() }
这里是一个例子,通过创build一个从CIImage创build的CGImage来创build一个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)