Swift 计算上下文中绘制的文本大小(核心图形)?

Swift 计算上下文中绘制的文本大小(核心图形)?,swift,Swift,我需要知道我将在上下文中绘制的文本的大小。如何在上下文中找到已创建文本的大小 我应该为sizeOfText添加什么 这是我的代码: let text = "Some test" let locationOfText: CGPoint = .zero let fontOFText: CGFloat = 30 let paragraphStyle = NSMutableParagraphStyle() paragraphStyle.alignment = .left let at

我需要知道我将在上下文中绘制的文本的大小。如何在上下文中找到已创建文本的大小

我应该为sizeOfText添加什么

这是我的代码:

let text = "Some test"
let locationOfText: CGPoint = .zero
let fontOFText: CGFloat = 30
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.alignment = .left
let attrib: [NSAttributedString.Key: Any] = [
    .font: UIFont.boldSystemFont(ofSize: fontOFText),
    .paragraphStyle: paragraphStyle]
let sizeOfComponent = labelSimulator(withThisFont: UIFont.boldSystemFont(ofSize: fontOFText), withThisText: text)
let sizeOfText = CGSize(width: sizeOfComponent.width, height: sizeOfComponent.height)

text.draw(in: CGRect(origin: locationOfText, size: sizeOfText), withAttributes: Attrib)
这部分是我找到文字大小的方法,你知道更好的方法吗,点击我

//█ █ █ █ █ █ █ █ █ █ █ █ █ █ █ █ █ █ █ █ █ █ █ █ █ █ █ █ █ █
func labelSimulator(withThisFont: UIFont, withThisText: String) -> CGSize
{
    
    //▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲
    let simulator = UILabel()
    simulator.font = withThisFont
    simulator.text = withThisText
    //▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼
    
    //▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲
    return simulator.sizeThatFits(CGSize(width: CGFloat.greatestFiniteMagnitude, height: CGFloat.greatestFiniteMagnitude))
    //▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼
    
}
//█ █ █ █ █ █ █ █ █ █ █ █ █ █ █ █ █ █ █ █ █ █ █ █ █ █ █ █ █ █

对于您描述的特定情况,您通常需要的大小是
CGSize(宽度:.greatestfinitemagnity,高度:.greatestfinitemagnity)
。根据要绘制的上下文,可能需要约束高度。如果要将其包裹,则可以约束宽度

此处:中的
参数是一个约束框。这是允许的最大的盒子。它不必与文本紧密匹配

如果需要实际大小(例如,为了在其周围放置轮廓),可以使用
.boundingRect(with:options:attributes:context:)
计算

(注意您的编辑,您似乎有正确的想法。您不需要标签。您可以直接询问字符串。)

例如,根据您的代码,不需要labelSimulator:

let sizeOfText = CGSize(width: CGFloat.greatestFiniteMagnitude, height: .greatestFiniteMagnitude)
text.draw(in: CGRect(origin: locationOfText, size: sizeOfText), withAttributes: attrib)

对于您描述的特定情况,您通常需要的大小是
CGSize(宽度:.greatestfinitemagnity,高度:.greatestfinitemagnity)
。根据要绘制的上下文,可能需要约束高度。如果要将其包裹,则可以约束宽度

此处:
中的
参数是一个约束框。这是允许的最大的盒子。它不必与文本紧密匹配

如果需要实际大小(例如,为了在其周围放置轮廓),可以使用
.boundingRect(with:options:attributes:context:)
计算

(注意您的编辑,您似乎有正确的想法。您不需要标签。您可以直接询问字符串。)

例如,根据您的代码,不需要labelSimulator:

let sizeOfText = CGSize(width: CGFloat.greatestFiniteMagnitude, height: .greatestFiniteMagnitude)
text.draw(in: CGRect(origin: locationOfText, size: sizeOfText), withAttributes: attrib)

我已经向您展示了如何计算您的文本在屏幕上的高度。你只需要给它加一个边距,然后继续前进。您选择的宽度将决定最终高度:

let pdfFormat = UIGraphicsPDFRendererFormat()
let metaData: [CFString : Any] = [
                kCGPDFContextTitle: "Hello, World!",
                kCGPDFContextAuthor: "Omid",
                kCGPDFContextCreator: "PDF Creator"]
pdfFormat.documentInfo = metaData as [String: Any]
// your PDF page size
let size: CGSize = .init(width: 8.5 * 72.0, height: 11 * 72.0)
let bounds: CGRect = .init(origin: .zero, size: size)
let pdfRenderer = UIGraphicsPDFRenderer(bounds: bounds, format: pdfFormat)
let documentDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!

    let data = pdfRenderer.pdfData { (context) in
            context.beginPage()
    let text = "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum."
    let fontOFText: CGFloat = 30
    let paragraphStyle = NSMutableParagraphStyle()
    paragraphStyle.alignment = .left
    let attrib: [NSAttributedString.Key: Any] = [
        .font: UIFont.boldSystemFont(ofSize: fontOFText),
        .paragraphStyle: paragraphStyle]
    let margin: CGFloat = 20
    let attributedText = NSAttributedString(string: text, attributes: attrib)
    let textCanvas = bounds.insetBy(dx: margin, dy: 0).size
    let textSize = attributedText.boundingRect(with: textCanvas,
                                             options: [.usesFontLeading, .usesLineFragmentOrigin],
                                             context: nil).size
    let rect = CGRect(origin: .init(x: margin/2, y: 0), size: textSize)
    text.draw(in: rect, withAttributes: attrib)
    let nextTextYPosition = rect.origin.y + rect.size.height
    print("nextTextYPosition", nextTextYPosition)
    "NEXT TEXT".draw(in: .init(origin: .init(x: margin/2, y: nextTextYPosition), size: CGSize.init(width: 200, height: 200)), withAttributes: attrib)
}

let fileURL = documentDirectory.appendingPathComponent("test.pdf")
try data.write(to: fileURL)

我已经向您展示了如何计算屏幕上文本的高度。你只需要给它加一个边距,然后继续前进。您选择的宽度将决定最终高度:

let pdfFormat = UIGraphicsPDFRendererFormat()
let metaData: [CFString : Any] = [
                kCGPDFContextTitle: "Hello, World!",
                kCGPDFContextAuthor: "Omid",
                kCGPDFContextCreator: "PDF Creator"]
pdfFormat.documentInfo = metaData as [String: Any]
// your PDF page size
let size: CGSize = .init(width: 8.5 * 72.0, height: 11 * 72.0)
let bounds: CGRect = .init(origin: .zero, size: size)
let pdfRenderer = UIGraphicsPDFRenderer(bounds: bounds, format: pdfFormat)
let documentDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!

    let data = pdfRenderer.pdfData { (context) in
            context.beginPage()
    let text = "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum."
    let fontOFText: CGFloat = 30
    let paragraphStyle = NSMutableParagraphStyle()
    paragraphStyle.alignment = .left
    let attrib: [NSAttributedString.Key: Any] = [
        .font: UIFont.boldSystemFont(ofSize: fontOFText),
        .paragraphStyle: paragraphStyle]
    let margin: CGFloat = 20
    let attributedText = NSAttributedString(string: text, attributes: attrib)
    let textCanvas = bounds.insetBy(dx: margin, dy: 0).size
    let textSize = attributedText.boundingRect(with: textCanvas,
                                             options: [.usesFontLeading, .usesLineFragmentOrigin],
                                             context: nil).size
    let rect = CGRect(origin: .init(x: margin/2, y: 0), size: textSize)
    text.draw(in: rect, withAttributes: attrib)
    let nextTextYPosition = rect.origin.y + rect.size.height
    print("nextTextYPosition", nextTextYPosition)
    "NEXT TEXT".draw(in: .init(origin: .init(x: margin/2, y: nextTextYPosition), size: CGSize.init(width: 200, height: 200)), withAttributes: attrib)
}

let fileURL = documentDirectory.appendingPathComponent("test.pdf")
try data.write(to: fileURL)


原点:.0
。关于文本的大小,它将取决于字体的大小。我编辑了我的代码,我知道我的字体大小,现在如何确定?您必须至少决定标签的宽度。这取决于你的大小,它将是drawnYes我知道,我可以给像CGSize(宽度:400,高度:100),但什么是正确的需要的大小?你必须给它一个地方写。这就像你的页面大小一样。它将尽可能多地绘制原点:.0
。关于文本的大小,它将取决于字体的大小。我编辑了我的代码,我知道我的字体大小,现在如何确定?您必须至少决定标签的宽度。这取决于你的大小,它将是drawnYes我知道,我可以给像CGSize(宽度:400,高度:100),但什么是正确的需要的大小?你必须给它一个地方写。这就像你的页面大小一样。你能按我的方式重构吗?我不知道这意味着什么。你的方式是什么?labelSimulator我是说你能重构我的方式吗?我不知道那意味着什么。你的方法是什么?labelSimulator我是说谢谢Leo,你能解释一下(选项:[.UseSFuntleding,.usesLineFragmentOrigin])和(上下文:nil)我用[]替换了选项,也工作了,它们是什么吗?我看了Xcode的内容,但我不明白。谢谢Leo,你能解释一下(选项:[.UseSFuntleding,.usesLineFragmentOrigin])和(上下文:nil)我用[]替换了选项,并且还工作了,它们是什么吗?我看了看Xcode是怎么说的,但我不明白。