0

我有一个问题。是否可以打印仅临时保存的图像?我保存了图像,因为它在这个关于 stackoverflow 的问题示例中完成。

但是当我尝试使用这张图片通过 AirPrint 进行打印时,它不起作用。

- (IBAction)btnPrintTapped:(id)sender {

    UIImage* image = nil;

    UIGraphicsBeginImageContext(_scrollView.contentSize);
    {
        CGPoint savedContentOffset = _scrollView.contentOffset;
        CGRect savedFrame = _scrollView.frame;

        _scrollView.contentOffset = CGPointZero;
        _scrollView.frame = CGRectMake(0, 0, _scrollView.contentSize.width, _scrollView.contentSize.height);

        [_scrollView.layer renderInContext: UIGraphicsGetCurrentContext()];
        image = UIGraphicsGetImageFromCurrentImageContext();

        _scrollView.contentOffset = savedContentOffset;
        _scrollView.frame = savedFrame;
    }
    UIGraphicsEndImageContext();

    if (image != nil) {
        [UIImagePNGRepresentation(image) writeToFile: @"/tmp/test.png" atomically: YES];
        UIImage *yourImage = [UIImage imageNamed:@"/tmp/test.png"];
        NSArray *itemsToShare = @[yourImage];
        UIActivityViewController *activityVC = [[UIActivityViewController alloc] initWithActivityItems:itemsToShare applicationActivities:nil];
        activityVC.excludedActivityTypes = @[ UIActivityTypeCopyToPasteboard, UIActivityTypeAssignToContact, UIActivityTypeSaveToCameraRoll, UIActivityTypeMail, UIActivityTypeMessage, UIActivityTypePostToFacebook, UIActivityTypePostToTwitter, UIActivityTypePostToWeibo]; 
        [self presentViewController:activityVC animated:YES completion:nil];
    }    
}

但是打印机能够打印(我用修复图像对其进行了测试)......所以打印机似乎不是问题。提前感谢您的帮助。

更新 我对代码做了一些更改/添加了一些代码行:

[UIImagePNGRepresentation(image) writeToFile: @"/tmp/test.png" atomically: YES];

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString* path = [documentsDirectory stringByAppendingPathComponent:@"/tmp/test.png" ];
UIImage* image = [UIImage imageWithContentsOfFile:path];

UIImage *ImageItem = image;

但它只在我设置时才有效writeToFile: @"test.png"......但是我只能保存一次图像而不能覆盖它。

当我使用上面的代码执行此操作时,会出现一个错误

由于未捕获的异常“NSInvalidArgumentException”而终止应用程序,原因:“-[__NSPlaceholderArray initWithObjects:count:]:尝试从对象 [0] 插入 nil 对象”

4

1 回答 1

0

经过一番尝试,它现在终于可以工作了......

if (image != nil) {
        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
                                                             NSUserDomainMask, YES);
        NSString *documentsDirectory = [paths objectAtIndex:0];
        NSString* path = [documentsDirectory stringByAppendingPathComponent:
                          @"test.png" ];
        NSData* data = UIImagePNGRepresentation(image);
        [data writeToFile:path atomically:YES];


        UIImage* image = [UIImage imageWithContentsOfFile:path];
        UIImage *yourImage = image;
于 2013-07-21T12:51:19.313 回答