在iOS上绘制旋转文本会创建跳跃字符

时间:2011-11-07 17:58:34

标签: ios text drawing core-graphics

我试图在iOS平台上使用Core Graphics绘制稍微旋转的文本。文本在不旋转时呈现正常,但渲染系统会尝试锁定旋转文本的像素。

例如:如果将Core Graphics上下文旋转一些少量(如2度)然后绘制文本,则单个字符将显示为向上和向下跳跃,因为Core Graphics将字符锁定为像素(字体提示)。我知道如果文本不能锁定像素网格,文本可能会变得模糊,但这是可以接受的。跳跃的字符不是。那么如何禁用垂直字体提示?提示水平可以,但完全关闭它也可以。


自定义UIView的代码:

- (void)drawRect:(CGRect)rect {
    CGContextRef context = UIGraphicsGetCurrentContext();
    [self.backgroundColor setFill];
    CGContextFillRect(context, rect);
    CGContextSaveGState(context);
    // rotate context
    CGContextTranslateCTM(context, self.bounds.size.width / 2.0, self.bounds.size.width / 2.0);
    CGContextRotateCTM(context, 2.0 * M_PI / 180.0);
    CGContextTranslateCTM(context, -self.bounds.size.width / 2.0, -self.bounds.size.width / 2.0);

    [[UIColor blackColor] setFill];
    [self.title drawInRect:[self bounds] withFont:[UIFont systemFontOfSize:15.0]];
    CGContextRestoreGState(context);
}

结果(不完全是这段代码,但类似的,红线插入以引导“错误”):

Image of the jumping characters

1 个答案:

答案 0 :(得分:1)

我找到的唯一解决方案是使用Core Text获取字形的实际Bezier路径并绘制那些绕过任何垂直提示的路径。以下代码摘录相当冗长:

CGRect textRect = CGRectMake(0.0, 0.0, 300.0, 190.0);
CGContextRef context = UIGraphicsGetCurrentContext();

// Flip coordinate system vertically.
CGContextSaveGState(context);
CGFloat rectHeight = textRect.size.height;
CGContextTranslateCTM(context, 0.0, rectHeight);
CGContextScaleCTM(context, 1.0f, -1.0f);

// Positive degrees because of flip.
CGAffineTransform rotationTransform = CGAffineTransformMakeRotation(2.0 * M_PI/180.0);
CGContextConcatCTM(context, rotationTransform);


CGFloat pointSize = 15.0;
CTFontRef font = CTFontCreateUIFontForLanguage(kCTFontSystemFontType, 
                                               pointSize, 
                                               NULL);

CGContextSetTextMatrix(context, CGAffineTransformIdentity);

NSDictionary *initialAttributes = (
                                   @{
                                     (NSString *)kCTFontAttributeName            : (__bridge id)font,
                                     (NSString *)kCTForegroundColorAttributeName : (__bridge id)[UIColor blackColor].CGColor
                                     }
                                   );

NSMutableAttributedString *attributedString = 
[[NSMutableAttributedString alloc] initWithString:[self string]
                                       attributes:initialAttributes];


//
// For typesetting a frame, we should create a paragraph style.
// Includes fix for CTFramesetter’s wrong line spacing behavior.
// See Technical Q&A QA1698: “How do I work-around an issue where some lines
// in my Core Text output have extra line spacing?”
//

// Center alignment looks best when filling an ellipse.
CTTextAlignment alignment = kCTLeftTextAlignment;
CTLineBreakMode lineBreakMode = kCTLineBreakByWordWrapping;

// This is the leading in the historical sense, which is added to the point
// size but does not include it like the line height does.
CGFloat leading = 2.0;

// Still, for the fix we do need the line height.
CGFloat lineHeight = pointSize + leading;

CTParagraphStyleSetting paragraphStyleSettings[] =
{
    {
        kCTParagraphStyleSpecifierAlignment,
        sizeof(alignment),
        &alignment
    },

    {
        kCTParagraphStyleSpecifierLineBreakMode,
        sizeof(lineBreakMode),
        &lineBreakMode
    },

    // These two specifiers fix the line spacing when set to line height.
    {
        kCTParagraphStyleSpecifierMinimumLineHeight,
        sizeof(lineHeight),
        &lineHeight
    },

    {
        kCTParagraphStyleSpecifierMaximumLineHeight,
        sizeof(lineHeight),
        &lineHeight
    }

    // Very important: Do not set kCTParagraphStyleSpecifierLineSpacing too,
    // or it will be added again!
};

CTParagraphStyleRef paragraphStyle = CTParagraphStyleCreate(
                                                            paragraphStyleSettings,
                                                            sizeof(paragraphStyleSettings) / sizeof(paragraphStyleSettings[0])
                                                            );

// Apply paragraph style to entire string. This cannot be done when the
// string is empty, by the way, because attributes can only be applied to
// existing characters.
NSRange stringRange = NSMakeRange(0, [attributedString length]);

[attributedString addAttribute:(NSString *)kCTParagraphStyleAttributeName 
                         value:(__bridge id)(paragraphStyle) 
                         range:stringRange];


// Create bezier path to contain our text.
CGMutablePathRef path = CGPathCreateMutable();
CGPathAddRect(path, NULL, textRect);

CTFramesetterRef framesetter = CTFramesetterCreateWithAttributedString((__bridge CFAttributedStringRef)(attributedString));

// Range with length 0 indicates that we want to typeset until we run out of
// text or space.
CTFrameRef frame = CTFramesetterCreateFrame(
                                            framesetter, 
                                            CFRangeMake(0, 0), 
                                            path, 
                                            NULL
                                            );


CFArrayRef lines = CTFrameGetLines(frame);
CFIndex lineCount = CFArrayGetCount(lines);
CFRange range = CFRangeMake(0, 0);
CGPoint lineOrigins[lineCount];
CTFrameGetLineOrigins(frame, range, lineOrigins);

for (NSUInteger lineIndex = 0; lineIndex < lineCount; ++lineIndex)
{
    CTLineRef line = CFArrayGetValueAtIndex(lines, lineIndex);
    CGPoint lineOrigin = lineOrigins[lineIndex];
    CFArrayRef runs = CTLineGetGlyphRuns(line);
    CFIndex runCount = CFArrayGetCount(runs);

    for (NSUInteger runIndex = 0; runIndex < runCount; ++runIndex)
    {
        CTRunRef run = CFArrayGetValueAtIndex(runs, runIndex);
        CFIndex glyphCount = CTRunGetGlyphCount(run);

        CGGlyph glyphBuffer[glyphCount];
        CTRunGetGlyphs(run, range, glyphBuffer);

        CGPoint positionsBuffer[glyphCount];
        CTRunGetPositions(run, range, positionsBuffer);

        for (NSUInteger glyphIndex = 0; glyphIndex < glyphCount; ++glyphIndex)
        {
            CGGlyph glyph = glyphBuffer[glyphIndex];
            CGPoint position = positionsBuffer[glyphIndex];
            CGAffineTransform positionTransform = CGAffineTransformMakeTranslation(lineOrigin.x + position.x, 
                                                                                   lineOrigin.y + position.y);
            CGPathRef glyphPath = CTFontCreatePathForGlyph(font, glyph, &positionTransform);
            CGContextAddPath(context, glyphPath);
        }
    }
}

CGContextSetFillColorWithColor(context, [UIColor blackColor].CGColor);
CGContextFillPath(context);


CFRelease(font);
CFRelease(framesetter);

// Use specialized release function when it exists.
CGPathRelease(path);

CGContextRestoreGState(context);