2012-04-19 1 views
4

В настоящее время я работаю над возможностью распечатать содержимое представления через Airprint. Для этой функции я создаю UIImage из представления и отправлю его в UIPrintInteractionController.Resize UIImage для UIPrintInteractionController

Проблема заключается в том, что изображение изменяется до полного разрешения бумаги, а не оригинального размера (приблизительно 300x500 пикселей). Кто-нибудь знает, как создать правильную страницу из моего изображения.

Вот код:

/** Create UIImage from UIScrollView**/ 
-(UIImage*)printScreen{ 
UIImage* img = 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.backgroundColor = [UIColor whiteColor]; 
    [scrollView.layer renderInContext: UIGraphicsGetCurrentContext()];  
    img = UIGraphicsGetImageFromCurrentImageContext(); 

    scrollView.contentOffset = savedContentOffset; 
    scrollView.frame = savedFrame; 
    scrollView.backgroundColor = [UIColor clearColor]; 
} 
UIGraphicsEndImageContext(); 
return img; 
} 

/** Print view content via AirPrint **/ 
-(void)doPrint{ 
if ([UIPrintInteractionController isPrintingAvailable]) 
{ 
    UIPrintInteractionController *pic = [UIPrintInteractionController sharedPrintController]; 

    UIImage *image = [(ReservationOverView*)self.view printScreen]; 

    NSData *myData = [NSData dataWithData:UIImagePNGRepresentation(image)]; 
    if(pic && [UIPrintInteractionController canPrintData: myData]) { 

     pic.delegate =(id<UIPrintInteractionControllerDelegate>) self; 

     UIPrintInfo *printInfo = [UIPrintInfo printInfo]; 
     printInfo.outputType = UIPrintInfoOutputPhoto; 
     printInfo.jobName = [NSString stringWithFormat:@"Reservation-%@",self.reservation.reservationID]; 
     printInfo.duplex = UIPrintInfoDuplexNone; 
     pic.printInfo = printInfo; 
     pic.showsPageRange = YES; 
     pic.printingItem = myData; 
     //pic.delegate = self; 

     void (^completionHandler)(UIPrintInteractionController *, BOOL, NSError *) = ^(UIPrintInteractionController *printController, BOOL completed, NSError *error) { 
      if (!completed && error) { 
       NSLog(@"FAILED! due to error in domain %@ with error code %u", error.domain, error.code); 
      } 
     }; 

     [pic presentAnimated:YES completionHandler:completionHandler]; 

    } 

} 
} 

Я пытался изменить размер изображения вручную, но это не работает должным образом.

+0

Я нашел одно нетривиальное решение и добавил изображение в самоподготовленный файл pdf, но я хотел бы знать, возможно ли это без файла pdf. – AlexVogel

ответ

1

Я нашел этот пример кода на Apple:

https://developer.apple.com/library/ios/samplecode/PrintPhoto/Listings/Classes_PrintPhotoPageRenderer_m.html#//apple_ref/doc/uid/DTS40010366-Classes_PrintPhotoPageRenderer_m-DontLinkElementID_6

И это выглядит как правильный способ размера изображения для печати (так не заполняет всю страницу) заключается в реализации собственного UIPrintPageRenderer и реализации:

- (void)drawPageAtIndex:(NSInteger)pageIndex inRect:(CGRect)printableRect 

printableRect сообщит вам размер бумаги, и вы можете масштабировать его вниз насколько вы хотите (предположительно, вычисляя некоторый ДОИ).

Update: Я в конечном итоге реализации моего собственного ImagePageRenderer:

- (void)drawPageAtIndex:(NSInteger)pageIndex inRect:(CGRect)printableRect 
{ 
    if(self.image) 
    { 
     CGSize printableAreaSize = printableRect.size; 

     // Apple uses 72dpi by default for printing images. This 
     // renders out the image to be giant. Instead, we should 
     // resize our image to our desired dpi. 
     CGFloat dpiScale = kAppleDPI/self.dpi; 

     CGFloat imageWidth = self.image.size.width * dpiScale; 
     CGFloat imageHeight = self.image.size.height * dpiScale; 

     // scale image if paper is too small 
     BOOL scaleImage = printableAreaSize.width < imageWidth || printableAreaSize.height < imageHeight; 
     if(scaleImage) 
     { 
      CGFloat widthScale = (CGFloat)printableAreaSize.width/imageWidth; 
      CGFloat heightScale = (CGFloat)printableAreaSize.height/imageHeight; 

      // Choose smaller scale so there's no clipping 
      CGFloat scale = widthScale < heightScale ? widthScale : heightScale; 

      imageWidth *= scale; 
      imageHeight *= scale; 
     } 

     // If you want to center vertically, horizontally, or both, 
     // modify the origin below. 

     CGRect destRect = CGRectMake(printableRect.origin.x, 
             printableRect.origin.y, 
             imageWidth, 
             imageHeight); 

     // Use UIKit to draw the image to destRect. 
     [self.image drawInRect:destRect]; 
    } 
    else 
    { 
     NSLog(@"no image to print"); 
    } 
} 
0
UIImage *image = [UIImage imageNamed:@"myImage"]; 
    [image drawInRect: destinationRect]; 
    UIImage *thumbnail = UIGraphicsGetImageFromCurrentImageContext(); 
UIImageWriteToSavedPhotosAlbum(image,nil,nil,nil); 

destinationRect будет иметь размеры в соответствии с размерами урезанной версии.

 Смежные вопросы

  • Нет связанных вопросов^_^