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;
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 175,151评论 25 709
  • 还未下班,他就已经编好了发给他老婆的微信,一条他第一次如此投入的向他老婆敞开自己心扉的信息,尽管此前他并没有想着要...
    城市屋檐下阅读 1,462评论 0 1
  • 使管理者缺乏有效性的第三项现实因素,是管理者本身处于一个“组织”之中。只有当别人能够利用管理者的贡献时,管理...
    huangdan阅读 1,391评论 0 0
  • 文|秋思说财 未经允许 不得转载 最近有不少新粉丝加入,后台留言说,对多赚钱理财一窍不通,还有说看了我的文章,还是...
    秋思说阅读 7,659评论 4 12
  • 我想,风雨便是这世间最惊世的爱情。 雨 你 来的酣畅淋漓 风 我 淋的一病不起 雨停 把思念熬成相思 风吟 把喜欢...
    风四火阅读 4,125评论 0 5