【问题标题】:Which method to use to display text ?Why?使用哪种方法显示文本?为什么?
【发布时间】:2013-05-10 10:28:43
【问题描述】:

使用 CoreGraphics 绘制字符串/标签时,我们有 2 种方法

- (CGSize)drawInRect:(CGRect)rect withFont:(UIFont *)font lineBreakMode:(NSLineBreakMode)lineBreakMode alignment:(NSTextAlignment)alignment;

例如:

   [value drawInRect:CGRectMake(xValue, rect.origin.y, objLegends.value *singleUnitWidth,heightOfBar)
                 withFont:[UIFont systemFontOfSize:10.0f]
            lineBreakMode:NSLineBreakByClipping
                alignment:NSTextAlignmentCenter];

CG_EXTERN void CGContextShowText(CGContextRef c, const char *string,
    size_t length) CG_AVAILABLE_STARTING(__MAC_10_0, __IPHONE_2_0);

例如

        CGContextSaveGState(context);
        // Tanslate and scale upside-down to compensate for Quartz's inverted coordinate system
        CGContextSetTextMatrix(context, CGAffineTransformMake(1.0,0.0, 0.0, -1.0, 0.0, 0.0));

        CGContextSelectFont(context, "Helvetica", 10.0f, kCGEncodingMacRoman);
        CGContextSetTextDrawingMode(context, kCGTextFill);
        CGContextSetTextPosition(context, xValue, rect.size.height-heightOfText);


        if ([value canBeConvertedToEncoding:NSMacOSRomanStringEncoding])
        {
            CGContextShowText(context, [value cStringUsingEncoding:NSMacOSRomanStringEncoding],5);
            //                              strlen([value cStringUsingEncoding:NSMacOSRomanStringEncoding]));
        }
        CGContextRestoreGState(context);

哪种方法好,为什么?

【问题讨论】:

  • 其中只有一个是方法,还有很多不止两个。 NSString 方法相对于 CGContext 函数的一个明显优势是,对于后者,您必须尝试在 MacRoman 中对字符串进行编码,这可能会失败。 NSString 方法、其对应的 NSAttributedString 和 Core Text 都支持 Unicode。

标签: iphone ios objective-c ipad core-graphics


【解决方案1】:

最好的方法是最容易实现目标的方法。您可以使用的 API 级别越高越好。如果您可以使用 NSString 方法,那么您应该 - 除非您可以使用 UILabel(或类似方法)为您完成这项工作。始终尝试编写尽可能少的代码并重用为您提供的代码,如果您的需求或性能分析表明您需要,则放弃使用较低级别的 API。

【讨论】:

    猜你喜欢
    • 2021-08-03
    • 1970-01-01
    • 1970-01-01
    • 2023-02-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-14
    相关资源
    最近更新 更多