How can I make an UIImage programmatically?

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

    If you want to draw just an empty image, you could use UIKit UIImageBeginImageContextWithOptions: method.

        UIGraphicsBeginImageContext(CGSizeMake(width, height));
        CGContextAddRect(UIGraphicsGetCurrentContext(), CGRectMake(0, 0, width, height)); // this may not be necessary
        UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
    

    The code above assumes that you draw a image with a size of width x height. It adds rectangle into the graphics context, but it may not be necessary. Try it yourself. This is the way to go. :)

    Or, if you want to create a snapshot of your current view you would type code like;

     UIGraphicsBeginImageContext(CGSizeMake(self.view.size.width, self.view.size.height));
        [self.view.layer renderInContext:UIGraphicsGetCurrentContext()];
        UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
    

    Don't forget to include Quartz library if you use layer.

提交回复
热议问题