截取屏幕截图

时间:2012-03-22 17:56:29

标签: iphone objective-c ios xcode ios4

我需要拍摄一个屏幕截图并另存为pdf。我已经完成了保存为pdf任务,但我拍摄的屏幕截图总是给出一个空白的pdf。我不知道为什么。我的代码如下:

 -(IBAction)takeScreenShot
{
if ([[UIScreen mainScreen] respondsToSelector:@selector(scale)])
    UIGraphicsBeginImageContextWithOptions(self.view.bounds.size, NO, [UIScreen mainScreen].scale);
else
    UIGraphicsBeginImageContext(self.view.bounds.size);
[self.view.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIImageView *newImage = [[UIImageView alloc] initWithImage:image];
UIGraphicsEndImageContext();

[self createPDFfromUIView:newImage saveToDocumentsWithFileName:@"SecondScreen1.pdf"];
}


-(void)createPDFfromUIView:(UIImageView*)aView saveToDocumentsWithFileName:(NSString*)aFilename
{
// Creates a mutable data object for updating with binary data, like a byte array
NSMutableData *pdfData = [NSMutableData data];
//CGSize pageSize = CGSizeMake(612, 792);
// Points the pdf converter to the mutable data object and to the UIView to be converted
UIGraphicsBeginPDFContextToData(pdfData, aView.bounds, nil);
UIGraphicsBeginPDFPage();

// draws rect to the view and thus this is captured by UIGraphicsBeginPDFContextToData
//[aView.layer renderInContext:UIGraphicsGetCurrentContext()];

// remove PDF rendering context
UIGraphicsEndPDFContext();

// Retrieves the document directories from the iOS device
NSArray* documentDirectories = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask,YES);

NSString* documentDirectory = [documentDirectories objectAtIndex:0];
NSString* documentDirectoryFilename = [documentDirectory stringByAppendingPathComponent:aFilename];

// instructs the mutable data object to write its context to a file on disk
[pdfData writeToFile:documentDirectoryFilename atomically:YES];
NSLog(@"documentDirectoryFileName: %@",documentDirectoryFilename);
}

1 个答案:

答案 0 :(得分:3)

注释掉的这一行应该是将您的图像写入pdf。把这些代码放回去,它可能会有用。

[aView.layer renderInContext:UIGraphicsGetCurrentContext()];

如果失败(没有错误),请确保UIImage *图像不是空白。