代码之家  ›  专栏  ›  技术社区  ›  davbryn

使用NSString的drawAtPoint方法代替CGContextShowGlyphsAtPoint问题

  •  10
  • davbryn  · 技术社区  · 15 年前

    在我的应用程序中,我试图沿着路径呈现文本;这对于大多数字符来说是好的,但是对于日语(或者任何非mac-Roman的字符)来说是不行的。有人建议我使用[NSString drawAtPoint],它在我的CATiledLayer中显示正确的字符;然而,它们在大约5秒钟后消失了。在这段时间里,我可以缩放图层,它们可以适当地缩放,但它们似乎不像文本的其他部分那样被提交到CATiledLayer。

    在渲染之前,我检查字符串并确定其中是否有不可渲染的。如果我遇到问题,我会使用drawAtpoint:

    if (!isFullyDisplayable)
     {
      CGContextShowGlyphsAtPoint(context, pt.x, pt.y, realGlyph, 1);
     }
     else {
      // fall back on less flexible font rendering for difficult characters
    
      NSString *b = [gv text];
      NSString *c = [b substringWithRange:NSMakeRange(j,1)];
    
      [c drawAtPoint:pt withFont:[UIFont fontWithName:@"Helvetica-Bold" size:16.0]];
    
    
     }
    

    <Error>: CGContextGetShouldSmoothFonts: invalid context
    <Error>: CGContextSetFont: invalid context
    <Error>: CGContextSetTextMatrix: invalid context
    <Error>: CGContextSetFontSize: invalid context
    <Error>: CGContextSetTextPosition: invalid context
    <Error>: CGContextShowGlyphsWithAdvances: invalid context
    

    所以我猜这与我的上下文管理有关,但是我假设如果这与我使用CGContextShowGlyphsAtPoint的位置相同,那么它应该已经有了正确的上下文了?

    2 回复  |  直到 9 年前
        1
  •  17
  •   davbryn    15 年前

    NSString drawAtPoint:withFont:使用上下文堆栈,从我调用这个方法的地方,堆栈是空的。将呼叫包装为

    UIGraphicsPushContext(context); and UIGraphicsPopContext();
    

        2
  •  1
  •   Grimxn    9 年前

    .drawInRect ...

    CGContextSaveGState(context)
    let old_nsctx = NSGraphicsContext.currentContext() // in case there was one
    // force "my" context...
    NSGraphicsContext.setCurrentContext(NSGraphicsContext(CGContext: context, flipped: true)) 
    
    // Do any rotations, translations, etc. here
    str.drawAtPoint(cgPt, withAttributes: attributes)
    
    NSGraphicsContext.setCurrentContext(old_nsctx)// clean up for others
    CGContextRestoreGState(context)
    

    正如@davbryn所说,这基本上是不需要的 堆栈上已经有一个相同的“工作”上下文(希望如此!)然而,正如他所指出的,在你的上下文中,有时没有。我发现这个问题特别是在MapKit上 MKOverlayRenderer drawMapRect:

    推荐文章