How can I make an UIImage programmatically?

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

    You need to use CoreGraphics, as follows.

    CGSize size = CGSizeMake(desiredWidth, desiredHeight);
    UIGraphicsBeginImageContextWithOptions(size, YES, 0);
    [[UIColor whiteColor] setFill];
    UIRectFill(CGRectMake(0, 0, size.width, size.height));
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    

    The code creates a new CoreGraphics image context with the options passed as parameters; size, opaqueness, and scale. By passing 0 for scale, iOS automatically chooses the appropriate value for the current device.

    Then, the context fill colour is set to [UIColor whiteColor]. Immediately, the canvas is then actually filled with that color, by using UIRectFill() and passing a rectangle which fills the canvas.

    A UIImage is then created of the current context, and the context is closed. Therefore, the image variable contains a UIImage of the desired size, filled white.

提交回复
热议问题