我想在PDF文件上创建一个矩形,但我不知道如何做到这一点。它很容易创建一些文本或图像,但我想添加一些形状,如矩形和圆形。
UIGraphicsBeginPDFPageWithInfo 与CGContext相同吗?
目前我正在使用它:
UIGraphicsBeginPDFContextToFile(pdfFileName, CGRectZero, nil);
UIGraphicsBeginPDFPageWithInfo(CGRectMake(0, 0, 612, 792), nil);
// add some text
let mainTitle = "..."
mainTitle.drawInRect(CGRectMake(30, 110, 552, 40), withAttributes: textAttributesBoldLargeHeader)
但是如何添加自定义矩形?
答案 0 :(得分:4)
使用UIGraphicsGetCurrentContext()
获取PDF绘图上下文
并为它画任何东西。简单的例子:
UIGraphicsBeginPDFContextToFile(pdfFileName, CGRectZero, nil);
UIGraphicsBeginPDFPageWithInfo(CGRectMake(0, 0, 612, 792), nil);
let context = UIGraphicsGetCurrentContext()
CGContextSetFillColorWithColor(context, UIColor.blueColor().CGColor)
let rect = CGRect(x: 10, y: 10, width: 100, height: 200)
CGContextFillRect(context, rect)
UIGraphicsEndPDFContext()
答案 1 :(得分:2)
您还可以扩展UIView以呈现当前上下文并将数据保存为pdf文件:
Swift 3或更高版本
extension UIView {
var pdfData: Data {
let result = NSMutableData()
UIGraphicsBeginPDFContextToData(result, frame, nil)
guard let context = UIGraphicsGetCurrentContext() else { return result as Data }
UIGraphicsBeginPDFPage()
layer.render(in: context)
UIGraphicsEndPDFContext()
return result as Data
}
}
测试:
class ViewController: UIViewController {
let rectangle = UIBezierPath(rect: CGRect(x: 30, y: 110, width: 350, height: 40))
let shapeLayer = CAShapeLayer()
override func viewDidLoad() {
super.viewDidLoad()
shapeLayer.path = rectangle.cgPath
shapeLayer.strokeColor = UIColor.blue.cgColor
shapeLayer.fillColor = UIColor.red.cgColor
view.layer.addSublayer(shapeLayer)
do {
try view.pdfData.write(to: FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!.appendingPathComponent("view.pdf"), options: .atomic)
} catch {
print(error)
}
}
}