你的位置:首页 > 操作系统

[操作系统]iOS开发日记19


今天博主有一个截屏的需求,遇到了一些困难点,在此和大家分享,希望能够共同进步.

iOS7.0之后废除了之前常用的截屏方法,也新增了截屏的API.代码相对简单,今天就贴出来,大家自行研究.

1.

-(void) screenShot

{

    UIGraphicsBeginImageContext(self.view.bounds.size);

    [self.view.layer renderInContext:UIGraphicsGetCurrentContext()];

    UIImage *image= UIGraphicsGetImageFromCurrentImageContext();

    UIGraphicsEndImageContext();

    NSLog(@"image:%@",image);

    UIImageView *imaView = [[UIImageView alloc] initWithImage:image];

    imaView.frame = CGRectMake(0, 0, 100, 100);

    [self.view addSubview:imaView];

     UIImageWriteToSavedPhotosAlbum(image, self, nil, nil);

}

 2.

-(void)srceedShot2

{

    //延迟两秒保存

        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{

               //获取图形上下文

               //    UIGraphicsBeginImageContext(self.view.frame.size);

               UIGraphicsBeginImageContext(self.view.frame.size);

                //将view绘制到图形上下文中

        

                //    [self.view.layer renderInContext:UIGraphicsGetCurrentContext()];

                [self.view.layer renderInContext:UIGraphicsGetCurrentContext()];

        

             //将截屏保存到相册

                UIImage *newImage=UIGraphicsGetImageFromCurrentImageContext();

        

               UIImageWriteToSavedPhotosAlbum(newImage,self, @selector(image:didFinishSavingWithError:contextInfo:), nil);

           });}

 

 

//保存至相册后的回调

- (void)image: (UIImage *) image didFinishSavingWithError: (NSError *) error contextInfo: (void *) contextInfo

{

    NSString *msg =nil ;

    if(error){

        msg = @"保存图片失败" ;

    }else{

        msg = @"保存图片成功" ;

    }

    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"保存图片结果提示"

                                                   message:msg

                                                  delegate:self

                                         cancelButtonTitle:@"确定"

                                         otherButtonTitles:nil];

    [alert show];

}

 3.

-(void)screenShot3

{

    CGSize size = self.view.bounds.size;

    UIGraphicsBeginImageContextWithOptions(size, NO, [UIScreen mainScreen].scale);

    CGRect rec = CGRectMake(self.view.frame.origin.x, self.view.frame.origin.y, self.view.bounds.size.width, self.view.bounds.size.height);

    [self.view drawViewHierarchyInRect:rec afterScreenUpdates:YES];

    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();

    UIGraphicsEndImageContext();

    NSData * data = UIImagePNGRepresentation(image);

    NSString *path = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES).lastObject;

    NSString *filename = [path stringByAppendingPathComponent:@"foo.png"];

    [data writeToFile:filename atomically:YES];

    NSLog(@"***********%@",filename);

}