IOS屏幕截图的记录

虽然网上有很多不同的方法,但我还是写出来我自己写的一套,哈哈~
这段代码前前后后,写了一个多月,修修改改.中间测试的时候,总是出现很多bug.直到现在这个终极版.
写出好的代码,真的不容易.
1.这个是截取window上的代码:

UIWindow *screenWindow = [[UIApplication sharedApplication] keyWindow];
UIGraphicsBeginImageContextWithOptions(screenWindow.frame.size, NO, 0.0); // no ritina

CGContextRef context = UIGraphicsGetCurrentContext();

CGContextSaveGState(context);
for (UIWindow *window in [[UIApplication sharedApplication] windows]) {
    
    if(window == screenWindow)
    {
            break;
    }else{
        [window.layer renderInContext:context];
    }
}

//  //  ////////////////////////
if ([screenWindow respondsToSelector:@selector(drawViewHierarchyInRect:afterScreenUpdates:)]) {
    [screenWindow drawViewHierarchyInRect:screenWindow.bounds afterScreenUpdates:YES];
} else {
    [screenWindow.layer renderInContext:context];
}
CGContextRestoreGState(context);
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
screenWindow.layer.contents = nil;
UIGraphicsEndImageContext();

float iOSVersion = [UIDevice currentDevice].systemVersion.floatValue;
if(iOSVersion < 8.0)
{
    image = [self rotateUIInterfaceOrientationImage:image];
}

然后是上面代码中引用的一个方法,我自己写的,当屏幕旋转的时候,对图片进行一个旋转.

-(UIImage *)rotateUIInterfaceOrientationImage:(UIImage *)image{

UIInterfaceOrientation orientation = [[UIApplication sharedApplication] statusBarOrientation];
switch (orientation) {
    case UIInterfaceOrientationLandscapeRight:
    {
        LOG(@"右");
        image = [UIImage imageWithCGImage:image.CGImage scale:1 orientation:UIImageOrientationLeft];
    }
        break;
    case UIInterfaceOrientationLandscapeLeft:
    {
        LOG(@"左");
        image = [UIImage imageWithCGImage:image.CGImage scale:1 orientation:UIImageOrientationRight];
    }
        break;
    case UIInterfaceOrientationPortraitUpsideDown:
    {
        LOG(@"上");
        image = [UIImage imageWithCGImage:image.CGImage scale:1 orientation:UIImageOrientationDown];
    }
        break;
    case UIInterfaceOrientationPortrait:
    {
        LOG(@"下");
        image = [UIImage imageWithCGImage:image.CGImage scale:1 orientation:UIImageOrientationUp];
    }
        break;
    case UIInterfaceOrientationUnknown:
    {
        LOG(@"不知道");
    }
        break;
        
    default:
        break;
}

return image;
}

你可能感兴趣的:(IOS屏幕截图的记录)