2010年4月28日星期三

iPhone-屏幕截取

一、从View生成图片
-(void)captureScreen{
  // Begin
  UIGraphicsBeginImageContext(CGSizeMake(320,480));
  // Render
  CGContextRef ref = UIGraphicsGetCurrentContext(); 
  [self.view.layer renderInContext:ref];
  // Capture
  UIImage *tmpImage = UIGraphicsGetImageFromCurrentImageContext();
  // Display test
  //imgView.image = tmpImage;
  // nil test
  if (tmpImage == nil) {
    NSLog(@"nil returned");
  }
  // Size test
  //NSLog(@"size %f,%f",imgView.image.size.width,imgView.image.size.height);
  // Save
  //NSData *dataObj = UIImagePNGRepresentation(tmpImage);
  //[dataObj writeToFile:@"/Users/kiichi/Desktop/test1.png" atomically:NO];
  // Save 2
  //UIImageWriteToSavedPhotosAlbum(tmpImage,nil,nil,nil);
  UIImageWriteToSavedPhotosAlbum(tmpImage, self, @selector(image:didFinishSavingWithError:contextInfo:), nil);
  // End
  UIGraphicsEndImageContext();
}


- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo{
 //mSpining.hidden = true;
 if (error == nil) {
  UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"" message:@"Image has been saved"
                delegate:self cancelButtonTitle:@"OK" otherButtonTitles: nil];
  [alert show];
  [alert release];
 }
 else {
  UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"" 
                                                  message:[NSString stringWithFormat:@"ERROR: %@", [error localizedDescription]]
                                                 delegate:self 
                                        cancelButtonTitle:@"OK" 
                                        otherButtonTitles: nil];
  [alert show];
  [alert release];

 }
}
二、Screen Capture from the top level
(可以截取最顶层的屏幕图片,甚至可以截取摄像头的缓冲屏幕图片) To capture entire screen from the top level, even including the camera buffer:
1. Change file name to .mm from .m
2. Add extern

extern "C" CGImageRef UIGetScreenImage(); //私有api (官方已经允许使用,官方论坛声明地址:https://devforums.apple.com/message/149553)

3. Call UIGetScreenImage

  CGImageRef iref =  UIGetScreenImage();
  UIImage *tmpImage = [[UIImage alloc] initWithCGImage:iref];

发表评论