如何编写按钮,按下,将打印出Xcode中的整个ViewController?

时间:2014-04-12 22:50:07

标签: objective-c ios7

按下按钮时,我希望打印出整个当前的UIViewController。我该怎么编程呢?

我希望整个UIView能够在默认的AirPrint打印机上打印出来,或者在iDevice的照片库中保存为图像。我试图在网上找到答案,但没有提出任何问题。谢谢!

2 个答案:

答案 0 :(得分:2)

如果要添加它,请将其作为图像使用-drawViewHierarchyInRect:afterScreenUpdates:

当您点击按钮时,您可以使用以下方法:

-(void)didTapPrintButton:(id)sender
{
    UIGraphicsBeginImageContextWithOptions(self.view.bounds.size, NO, 0);
    [self.view drawViewHierarchyInRect:self.view.bound afterScreenUpdates:NO];
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    // Do something with 'image'
    UIImageWriteToSavedPhotosAlbum(image, self, @selector(image:didFinishSavingWithError:contextInfo:), NULL);
}

有关UIImageWriteToSavedPhotosAlbum的信息,请参阅docs

UIImageWriteToSavedPhotosAlbum的回调函数应该在同一个视图控制器中声明:

-(void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo
{
     // Image has been saved
}

答案 1 :(得分:2)

首先,您需要知道打印是否可用:

if ([UIPrintInteractionController isPrintingAvailable])
{
    [self printJob];

} else {

    // Printer not available
}

如果可用,您可以执行以下操作(使用类头文件上的UIPrintInteractionControllerDelegate):

-(void)printJob {

    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();
    UIGraphicsEndImageContext();
    NSData * data = UIImagePNGRepresentation(image);
    [data writeToFile:@"foo.png" atomically:YES];

    UIPrintInteractionController *pic = [UIPrintInteractionController sharedPrintController];
    pic.delegate = self;
    UIPrintInfo *printInfo = [UIPrintInfo printInfo];
    printInfo.outputType = UIPrintInfoOutputGeneral;
    printInfo.duplex = UIPrintInfoDuplexLongEdge;
    pic.printInfo = printInfo;
    pic.showsPageRange = YES;
    pic.printingItem = data;

    void (^completionHandler)(UIPrintInteractionController *, BOOL, NSError *) =
    ^(UIPrintInteractionController *printController, BOOL completed, NSError *error) {
        if (!completed && error) {
            NSLog(@"Printing didn't complete. Error: %@", error);
        }
    };
    UIBarButtonItem *barButton = [[UIBarButtonItem alloc]init];
    [pic presentFromBarButtonItem:barButton animated:YES completionHandler:completionHandler];

}