首页 > 解决方案 > PDFKit CGRect 剪辑到文本大小 SwiftUI

问题描述

我正在尝试在 PDF 文档的整个顶部填充颜色的标题。

无论我将 CGRect 设置为多大以剪辑到文本的边缘,标准行为似乎都是如此。

let attributes = [
      NSAttributedString.Key.font: UIFont.boldSystemFont(ofSize: 16),
      NSAttributedString.Key.backgroundColor : UIColor.red,
      NSAttributedString.Key.foregroundColor : UIColor.white
    ] 

let text = "Hello World!"
    text.draw(in: CGRect(x: 0, y: 10, width: 2000, height: 2000), withAttributes: attributes)

见附图。

我做了一个狡猾的解决方案,但对它不满意,因为用户可以复制“空格”而不是实际测试。真的不是一个优雅的解决方案:

let attributes = [
      NSAttributedString.Key.font: UIFont.boldSystemFont(ofSize: 16),
      NSAttributedString.Key.backgroundColor : UIColor.red,
      NSAttributedString.Key.foregroundColor : UIColor.white
    ]
    
    let attributesBack = [
      NSAttributedString.Key.font: UIFont.boldSystemFont(ofSize: 32),
      NSAttributedString.Key.backgroundColor : UIColor.red,
      NSAttributedString.Key.foregroundColor : UIColor.white
    ]
    
   
    let line = "                                                     "
    let text = "Hello World!"
    line.draw(in: CGRect(x: 0, y: 0, width: 2000, height: 2000), withAttributes: attributesBack)
    text.draw(in: CGRect(x: 0, y: 10, width: 2000, height: 2000), withAttributes: attributes)

Thera 是一种方式吗:要设置 CGRect 文本被绘制到整个页面上,就像 Spacer() 一样?湾。一种绘制实际矩形然后在其上绘制文本的方法?

谢谢在此处输入图像描述

标签: swiftcgrectios-pdfkit

解决方案


找到以下解决方案。使用 UIRectFill。

func drawHeader(_ drawContext: CGContext, pageRect: CGRect) {
  
  drawContext.saveGState()
  drawContext.setLineWidth(20.0)
    
    drawContext.addRect(CGRect(x: 0, y: 0, width: pageRect.width, height: pageRect.height))
    drawContext.setFillColor(red: 177.0/256.0, green: 205.0/256.0, blue: 220.0/256.0, alpha: 0.5)
    UIRectFill(CGRect(x: 0, y: 0, width: pageRect.width, height: pageRect.height))
  drawContext.saveGState()
  drawContext.restoreGState()
}


func myPDF() -> Data {
  let pdfMetaData = [
    kCGPDFContextCreator: "my PDF",
    kCGPDFContextAuthor: "etienne"
  ]
  let format = UIGraphicsPDFRendererFormat()
  format.documentInfo = pdfMetaData as [String: Any]
    let pageWidth = 595.2 //8.5 * 72.0
  let pageHeight = 841.8 //11 * 72.0
  let pageRect = CGRect(x: 0, y: 0, width: pageWidth, height: pageHeight)

  let renderer = UIGraphicsPDFRenderer(bounds: pageRect, format: format)
  
  let data = renderer.pdfData { (context) in
  
    context.beginPage()
   
    let attributes = [
      NSAttributedString.Key.font: UIFont.boldSystemFont(ofSize: 16),
      NSAttributedString.Key.backgroundColor : UIColor.red,
      NSAttributedString.Key.foregroundColor : UIColor.blue
    ]
    
    let text = "Hello World!"
    
    text.draw(in: CGRect(x: 0, y: 10, width: 2000, height: 2000), withAttributes: attributes)
    
    
    let context = context.cgContext
    drawHeader(context, pageRect: pageRect)
    
  }

  return data
}

推荐阅读