Search Unity

Getting Screen as UIImage (XCode) [Solved]

Discussion in 'iOS and tvOS' started by poolts, Jun 5, 2016.

  1. poolts

    poolts

    Joined:
    Aug 9, 2012
    Posts:
    110
    Hi all,

    I'm trying to figure out how to get a screenshot (don't need to save it, just store it in a variable) within xCode (not within Unity).

    The img variable just returns a white screen, so I'm thinking the code below isn't accessing the right view / window.

    Does anyone have any ideas how to get the screen as a UIImage within xCode?

    Code (csharp):
    1.         UIWindow *keyWindow = [[UIApplication sharedApplication] keyWindow];
    2.         CGRect rect = [keyWindow bounds];
    3.         UIGraphicsBeginImageContext(rect.size);
    4.         CGContextRef context = UIGraphicsGetCurrentContext();
    5.         [keyWindow.layer renderInContext:context];
    6.         UIImage *img = UIGraphicsGetImageFromCurrentImageContext();
    7.         UIGraphicsEndImageContext();
    Any help would be greatly appreciated.
     
  2. aihodge

    aihodge

    Joined:
    Nov 23, 2014
    Posts:
    131
    This code is from an old project so I'm not 100% sure that it will still work, but try:

    Code (CSharp):
    1. -(void)doScreenshot
    2. {
    3.     UIScreen *screen = [UIScreen mainScreen] ;
    4.     UIWindow *keyWindow = [[UIApplication sharedApplication] keyWindow];
    5.     UIView *view = [screen snapshotViewAfterScreenUpdates:YES];
    6.     UIGraphicsBeginImageContextWithOptions(screen.bounds.size, NO, 0);
    7.     [keyWindow drawViewHierarchyInRect:keyWindow.bounds afterScreenUpdates:YES];
    8.     UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    9.     UIGraphicsEndImageContext();
    10.     NSData *data= UIImagePNGRepresentation(image);
    11.     [data writeToFile:[NSString stringWithFormat:@"%@/ScreenShot.png",[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0]] atomically:YES];
    12. }
     
  3. poolts

    poolts

    Joined:
    Aug 9, 2012
    Posts:
    110
    Awesome that indeed works! Thanks a lot! :D
     
    aihodge likes this.
  4. aihodge

    aihodge

    Joined:
    Nov 23, 2014
    Posts:
    131
    That's great, and no problem!
     
unityunity