Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice
  3. Join us on November 16th, 2023, between 1 pm and 9 pm CET for Ask the Experts Online on Discord and on Unity Discussions.
    Dismiss Notice

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:
    113
    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:
    164
    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:
    113
    Awesome that indeed works! Thanks a lot! :D
     
    aihodge likes this.
  4. aihodge

    aihodge

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