我编写了一个模块,提供了几种方法来呈现文本和创建PDF文件。现在我发现使用核心文本和更高级别的文本呈现会弄乱核心文本布局的大小。后者主要表现为显示过大。你知道吗
场景:
CTRunDraw
(B)*呈现文本*)这会像预期的那样正确呈现。但前提是我之前不使用NSAttributedString
和drawAtPoint_
(a)绘制任何文本。你知道吗
这意味着,这两种方法各自都能完美地工作,但当它们结合在一起时,核心文本绘图会变得太大。你知道吗
在保存和恢复图形上下文时,有什么需要注意的吗?我几乎什么都试过了。我可以放一些代码在这里,但它是相当多的,在一个复杂的设置,所以如果你能指定你到底想看到什么,请让我知道。你知道吗
(A)高级文本绘图:
class Text(object):
def __init__(self, text="", font="Monaco", fontSize=12, position=None ):
self.text = text
self.font = font
self.fontSize = fontSize
self.position = position
self.fontRGBColor = 0, 1, 1, 1
def drawText(self):
textAttributes = {}
textAttributes[NSFontAttributeName] = NSFont.fontWithName_size_( self.font, self.fontSize )
textAttributes[NSForegroundColorAttributeName] = NSColor.colorWithCalibratedRed_green_blue_alpha_( *self.fontRGBColor )
textAttributedString = NSAttributedString.alloc().initWithString_attributes_( self.text, textAttributes )
textAttributedString.drawAtPoint_((self.position[0], self.position[1]))
(B)核心文本方法:
class TextBox(object):
def __init__(self):
self.font = "Monaco"
self.fontSize = 12
self.text = "This is my Text"
self.fontColor = 0, 1, 1, 0, 0.75
self.pdfContext = NSGraphicsContext.currentContext().graphicsPort()
def drawTextBox(self):
CGContextSaveGState(self.pdfContext)
myBounds = (0, 0), (100, 100)
posX, posY = myBounds[0]
width, height = myBounds[1]
self.fontObject = NSFont.fontWithName_size_(self.font, self.fontSize)
self.fontAttributes = {}
self.fontAttributes[NSFontAttributeName] = self.fontObject
self.fontAttributes[NSForegroundColorAttributeName] = NSColor.colorWithDeviceCyan_magenta_yellow_black_alpha_(*self.fontColor)
TextBoxWithFeaturesAttributedString = NSMutableAttributedString.alloc().initWithString_attributes_(self.text, self.fontAttributes)
setter = CTFramesetterCreateWithAttributedString(TextBoxWithFeaturesAttributedString)
path = CGPathCreateMutable()
CGPathAddRect(path, None, CGRectMake(0, 0, width, height))
box = CTFramesetterCreateFrame(setter, (0, 0), path, None)
ctLines = CTFrameGetLines(box)
origins = CTFrameGetLineOrigins(box, (0, len(ctLines)), None)
for i, (originX, originY) in enumerate(origins):
ctLine = ctLines[i]
bounds = CTLineGetImageBounds(ctLine, self.pdfContext)
if bounds.size.width == 0:
continue
ctRuns = CTLineGetGlyphRuns(ctLine)
for ctRun in ctRuns:
CGContextSetTextPosition(self.pdfContext, posX + originX, posY + originY)
CTRunDraw(ctRun, self.pdfContext, (0, 0))
CGContextRestoreGState(self.pdfContext)
在此表示衷心的感谢和感谢。你知道吗
目前没有回答
相关问题 更多 >
编程相关推荐