How can I make an UIImage programmatically?

前端 未结 5 1787
自闭症患者
自闭症患者 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:30

    Using the latest UIGraphics classes, and in swift, this looks like this (note the CGContextDrawPath that is missing in the answer from user1834305, this is the reason that is produces an transparant image) :

    static func imageWithSize(size : CGSize, color : UIColor) -> UIImage {
        UIGraphicsBeginImageContext(size)
        let context = UIGraphicsGetCurrentContext()
        CGContextSetFillColorWithColor(context, color.CGColor)
        CGContextAddRect(context, CGRect(x: 0, y: 0, width: size.width, height: size.height));
        CGContextDrawPath(context, .Fill)
        let image = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
        return image
    }
    

提交回复
热议问题