How to create a black UIImage?

后端 未结 5 1092
无人共我
无人共我 2021-02-08 21:42

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

相关标签:
5条回答
  • 2021-02-08 21:58

    Like this

    let image = UIGraphicsImageRenderer(size: bounds.size).image { _ in
          UIColor.black.setFill()
          UIRectFill(bounds)
    }
    

    As quoted in this WWDC vid

    There's another function that's older; UIGraphicsBeginImageContext. But please, don't use that.

    0 讨论(0)
  • 2021-02-08 22:00

    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).

    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();
    
    0 讨论(0)
  • 2021-02-08 22:07

    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()
    }
    
    0 讨论(0)
  • 2021-02-08 22:12

    Here is an example that creates a black UIImage that is 1920x1080 by creating it from a CGImage created from a CIImage:

    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)
    
    0 讨论(0)
  • 2021-02-08 22:15
    UIGraphicsBeginImageContextWithOptions(CGSizeMake(w,h), NO, 0);
    UIBezierPath* p =
        [UIBezierPath bezierPathWithRect:CGRectMake(0,0,w,h)];
    [[UIColor blackColor] setFill];
    [p fill];
    UIImage* im = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    

    Now im is the image.

    That code comes almost unchanged from this section of my book: http://www.apeth.com/iOSBook/ch15.html#_graphics_contexts

    0 讨论(0)
提交回复
热议问题