Saving UIView contents in iOS 4 with real size of the images inside (i.e. scale contentes up for save)

前端 未结 5 591
庸人自扰
庸人自扰 2020-12-05 01:34

I have an UIView with many UIImageViews as subviews. The app runs on iOS4 and I use images with retina display resolution (i.e. the images load with scale = 2)

I wa

5条回答
  •  天涯浪人
    2020-12-05 02:05

    Implementation for rendering any UIView to image (working also for retina display).

    helper.h file:

    @interface UIView (Ext) 
    - (UIImage*) renderToImage;
    @end
    

    and belonging implementation in helper.m file:

    #import 
    
    @implementation UIView (Ext)
    - (UIImage*) renderToImage
    {
      // IMPORTANT: using weak link on UIKit
      if(UIGraphicsBeginImageContextWithOptions != NULL)
      {
        UIGraphicsBeginImageContextWithOptions(self.frame.size, NO, 0.0);
      } else {
        UIGraphicsBeginImageContext(self.frame.size);
      }
    
      [self.layer renderInContext:UIGraphicsGetCurrentContext()];
      UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
      UIGraphicsEndImageContext();  
      return image;
    }
    

    0.0 is the scale factor. The scale factor to apply to the bitmap. If you specify a value of 0.0, the scale factor is set to the scale factor of the device’s main screen.

    QuartzCore.framework also should be put into the project because we are calling function on the layer object.

    To enable weak link on UIKit framework, click on the project item in left navigator, click the project target -> build phases -> link binary and choose "optional" (weak) type on UIKit framework.

    Here is library with similar extensions for UIColor, UIImage, NSArray, NSDictionary, ...

提交回复
热议问题