Xcode drawInRect根据RectSize拆分String

时间:2016-02-05 12:06:43

标签: xcode pdf dynamic split drawinrect

我想动态创建一个pdf。但是我对新页面有疑问。

目前我正在编写一个文本块,如果该文本块不适合剩余的Y位置 - 我将整个文本块写在新页面上。 但我想采取整个文本块,尽可能多地写入实际页面,并将其余内容写在新页面上。有人知道如何根据矩形尺寸拆分矩形文本吗?

这是代码: writeString ist来自CoreData,具有动态长度。

    func drawTextBlock(pdfFileName: String, writeString: NSString = " ", fontSize: CGFloat = 12.0, fontName: String = "Helvetica", textAlignment: NSTextAlignment = NSTextAlignment.Natural) {

    //Text attribute configuration
    let font = UIFont(name: fontName, size: fontSize)

    let textStyle = NSMutableParagraphStyle.defaultParagraphStyle().mutableCopy() as! NSMutableParagraphStyle
    textStyle.alignment = textAlignment

    let textFontAttributes = [
        NSFontAttributeName: font!,
        NSParagraphStyleAttributeName: textStyle
    ]
    let textSize = writeString.sizeWithAttributes(textFontAttributes)

    let linesNeeded = ceil(textSize.width / (myPageCalibration.pageWidth  - myPageCalibration.xOffsetLeft - myPageCalibration.xOffsetRight))


    if remainingSpaceY >= (textSize.height * linesNeeded) {
        //draw text in rectangle
        writeString.drawInRect(CGRectMake(myPageCalibration.xOffsetLeft, myPageCalibration.yOffsetUp + currentPositionY, myPageCalibration.pageWidth - myPageCalibration.xOffsetLeft - myPageCalibration.xOffsetRight, (textSize.height * linesNeeded )), withAttributes: textFontAttributes)

        //calc remainingSpace
        currentPositionY = CGFloat(linesNeeded * textSize.height) + currentPositionY
        remainingSpaceY = remainingSpaceY - (textSize.height * linesNeeded)
    }
    else {
        //next page
        UIGraphicsBeginPDFPageWithInfo(CGRectMake(0, 0, 595, 842), nil);
        remainingSpaceY = myPageCalibration.pageHeight - myPageCalibration.yOffsetDown - myPageCalibration.yOffsetUp
        currentPositionY = 0

        drawTextBlock(pdfFileName, writeString: writeString, fontSize: fontSize, fontName: fontName, textAlignment: textAlignment)
    }
}

0 个答案:

没有答案