swift – UIView的AirPrint内容
发布时间:2020-12-14 02:26:16 所属栏目:百科 来源:网络整理
导读:我正在尝试通过iPad应用程序设置打印,单击“打
我正在尝试通过iPad应用程序设置打印,单击“打印”将打印包含其所有内容的视图.以下是我尝试过的内容(通过网上的几个例子汇总):
// This is the View I want to print // Just a 200x200 blue square var testView = UIView(frame: CGRectMake(0,200,200)) testView.backgroundColor = UIColor.blueColor() let printInfo = UIPrintInfo(dictionary:nil)! printInfo.outputType = UIPrintInfoOutputType.General printInfo.jobName = "My Print Job" // Set up print controller let printController = UIPrintInteractionController.sharedPrintController() printController!.printInfo = printInfo // This is where I was thinking the print job got the // contents to print to the page?? printController?.printFormatter = testView.viewPrintFormatter() // Do it printController!.presentFromRect(self.frame,inView: self,animated: true,completionHandler: nil) 但是,我也读过here那个viewPrintFormatter只能用于UIWebView,UITextView和MKMapView,这是正确的吗? 当我用它打印(使用打印机模拟器)时,我只得到一个空页;试过各种打印机/纸张尺寸. 任何指导都非常感谢!
我不确定这是否是正确的方法,但我最终通过将视图转换为UIImage然后将其设置为打印控制器的printingItem来解决此问题.
更新的代码: // This is the View I want to print // Just a 200x200 blue square var testView = UIView(frame: CGRectMake(0,200)) testView.backgroundColor = UIColor.blueColor() let printInfo = UIPrintInfo(dictionary:nil)! printInfo.outputType = UIPrintInfoOutputType.General printInfo.jobName = "My Print Job" // Set up print controller let printController = UIPrintInteractionController.sharedPrintController() printController!.printInfo = printInfo // Assign a UIImage version of my UIView as a printing iten printController?.printingItem = testView!.toImage() // Do it printController!.presentFromRect(self.frame,completionHandler: nil) toImage()方法是UIView的扩展: extension UIView { func toImage() -> UIImage { UIGraphicsBeginImageContextWithOptions(bounds.size,false,UIScreen.mainScreen().scale) drawViewHierarchyInRect(self.bounds,afterScreenUpdates: true) let image = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return image } } 如果有人有,可以选择其他方法! (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |