代码之家  ›  专栏  ›  技术社区  ›  Austin Berenyi

NSLayoutConstraints可以用十进制常量呈现吗?

  •  0
  • Austin Berenyi  · 技术社区  · 5 年前

    我在UIScrollView中创建了几个uiview,它们根据我在Height和Width文本字段中键入的值动态调整大小。调整UIView的大小后,我将UIScrollView的内容保存为PDF数据。

    我发现PDF中UIView的维度(在Adobe Illustrator中测量时)总是四舍五入到三分之一。

    例如:

    1.5->1.333

    1.75->1.666

    每次更新约束之前我都会检查常量值,并且它们是准确的。有谁能解释一下为什么UIViews在作为PDF呈现时有不正确的维度?

    @IBAction func updateDimensions(_ sender: Any) {
    
            guard let length = NumberFormatter().number(from:
                lengthTextField.text ?? "") else { return }
    
            guard let width = NumberFormatter().number(from:
                widthTextField.text ?? "") else { return }
    
            guard let height = NumberFormatter().number(from:
                heightTextField.text ?? "") else { return }
    
            let flapHeight = CGFloat(truncating: width)/2
    
            let lengthFloat = CGFloat(truncating: length)
            let widthFloat = CGFloat(truncating: width)
            let heightFloat = CGFloat(truncating: height)
    
            UIView.animate(withDuration: 0.3) {
                self.faceAWidthConstraint.constant = lengthFloat
                self.faceAHeightConstraint.constant = heightFloat
                self.faceBWidthConstraint.constant = widthFloat
                self.faceA1HeightConstraint.constant = flapHeight
                self.view.layoutIfNeeded()
            }
        }
    
        func createPDFfrom(aView: UIView, saveToDocumentsWithFileName fileName: String)
        {
            let pdfData = NSMutableData()
            UIGraphicsBeginPDFContextToData(pdfData, aView.bounds, nil)
            UIGraphicsBeginPDFPage()
    
            guard let pdfContext = UIGraphicsGetCurrentContext() else { return }
    
            aView.layer.render(in: pdfContext)
            UIGraphicsEndPDFContext()
    
            if let documentDirectories = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first {
                let documentsFileName = documentDirectories + "/" + fileName
                debugPrint(documentsFileName)
                pdfData.write(toFile: documentsFileName, atomically: true)
            }
        }
    
    0 回复  |  直到 5 年前
        1
  •  1
  •   Josh Homann    5 年前

    你不应该用图层渲染(in:)以呈现pdf。它总是第三个是因为你必须在3x设备上(2x设备上是1/2,1x设备上是1),所以每个点有3个像素。当iOS将约束转换为像素时,它所能做的最好的事情就是四舍五入到最接近的三分之一,因为它选择一个整数像素。pdf可以有更高的像素密度(或者使用无限分辨率的矢量艺术),所以不用图层渲染(in:)将光栅化矢量层中的像素转储到PDF中,实际上应该手动将内容绘制到PDF上下文中(即使用UIBezier曲线,UIImage.draw文件等等)。这将允许pdf捕获您所拥有的任何光栅化图像的完全分辨率,并允许它捕获您使用的任何矢量,而不将它们降级为光栅化像素,这些像素受您碰巧所在的设备屏幕的约束。