How can I make an UIImage programmatically?

前端 未结 5 1794
自闭症患者
自闭症患者 2021-02-07 02:26

This isn\'t what you probably thought it was to begin with. I know how to use UIImage\'s, but I now need to know how to create a \"blank\" UIImage using:

CGRect sc

5条回答
  •  攒了一身酷
    2021-02-07 02:35

    Based on @HixField and @Rudolf Adamkovič answer. here's an extension which returns an optional, which I believe is the correct way to do this (correct me if I'm wrong!)?

    This extension allows you to create a an empty UIImage of what ever size you need (up to memory limit) with what ever fill color you want, which defaults to white, if you want the image to be the clear color you would use something like the following:

    let size = CGSize(width: 32.0, height: 32.0)
    if var image = UIImage.imageWithSize(size:size, UIColor.clear) {
        //image was successfully created, do additional stuff with it here.
    }
    

    This is for swift 3.x:

    extension UIImage {
         static func imageWithSize(size : CGSize, color : UIColor = UIColor.white) -> UIImage? {
             var image:UIImage? = nil
             UIGraphicsBeginImageContext(size)
             if let context = UIGraphicsGetCurrentContext() {
                   context.setFillColor(color.cgColor)
                   context.addRect(CGRect(origin: CGPoint.zero, size: size));
                   context.drawPath(using: .fill)
                   image = UIGraphicsGetImageFromCurrentImageContext();
            }
            UIGraphicsEndImageContext()
            return image
        }
    }
    

提交回复
热议问题