2017-08-31 63 views
0

我試圖在我的swift應用程序中將自定義UIView保存爲pdf,但是我失敗了。無法通過swift創建PDF與UIView?

所以我嘗試使用相同的方式與OC,它工作正常,但不與迅速。

這些是我的swift和OC測試代碼,它們都可以在模擬器和設備中顯示相同的塊。

迅速:

@objc class TestViewController: UIViewController { 
    override func viewDidAppear(_ animated: Bool) { 
     super.viewDidAppear(animated) 
     let sub = UIView(frame: CGRect(x: 10, y: 10, width: 100, height: 100)) 
     sub.backgroundColor = .red 
     view.addSubview(sub) 

     let data = NSMutableData() 
     UIGraphicsBeginPDFContextToData(data, view.bounds, nil) 
     UIGraphicsBeginPDFPage() 
     view.layer.draw(in: UIGraphicsGetCurrentContext()!) 
     UIGraphicsEndPDFContext() 

     let path = NSTemporaryDirectory() + "/pdftest_s.pdf" 
     data.write(toFile: path, atomically: true) 
     print(path) 
    } 
} 

OC:

#import <UIKit/UIKit.h> 

@interface ViewController : UIViewController 
@end 

@implementation ViewController 
- (void)viewDidAppear:(BOOL)animated { 
    [super viewDidAppear:animated]; 
    UIView *sub = [UIView.alloc initWithFrame:CGRectMake(10, 10, 100, 100)]; 
    sub.backgroundColor = UIColor.redColor; 
    [self.view addSubview:sub]; 

    NSMutableData *data = [NSMutableData data]; 
    UIGraphicsBeginPDFContextToData(data, self.view.bounds, nil); 
    UIGraphicsBeginPDFPage(); 
    [self.view.layer renderInContext:UIGraphicsGetCurrentContext()]; 
    UIGraphicsEndPDFContext(); 

    NSString *path = [NSTemporaryDirectory() stringByAppendingPathComponent:@"pdftest.pdf"]; 
    [data writeToFile:path atomically:YES]; 
    NSLog(@"%@", path); 
} 
@end 

在這兩種Xcode的8.3和9.0 beta6 OC工作正常,但不與迅速(3和4)。

我正在嘗試使用UIPrintPageRenderer,它不工作!

+1

有differance view.layer.draw和self.view.layer渲染嘗試修復它,然後再試 –

+0

它改變後呈現工作。謝謝。 –

回答

1

obj中的代碼要渲染view.layer

[self.view.layer renderInContext:UIGraphicsGetCurrentContext()]; 

而在SWIFT代碼,你忘了這樣做

與渲染代替view.layer.draw(in: UIGraphicsGetCurrentContext()!)

希望這是有幫助的

0

您需要在您當前的圖形上下文中呈現您的視圖。在swift3你可以做到這一點作爲

view.layer.render(in: UIGraphicsGetCurrentContext()!)

按照蘋果文檔

renderInContext:呈現層及其子層到 指定的上下文。