且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

是否可以使用Cocoa Touch改变字体的字母间距/字距调整?

更新时间:2023-02-02 09:17:01

我从谷歌到这里试图用UITextField做同样的事情。我实现了下面对UILabel一般工作的东西。

I landed here from Google trying to do the same with UITextField. I implemented something that'll work generically for UILabel below.

@interface AdjustableUILable : UILabel {
    CGFloat characterSpacing;
}

@property CGFloat characterSpacing;

@end


@implementation AdjustableUILable

@synthesize characterSpacing;

- (void)drawTextInRect:(CGRect)rect
{    
    if (characterSpacing)
    {
        // Drawing code
        CGContextRef context = UIGraphicsGetCurrentContext();
        CGFloat size = self.font.pointSize;

        CGContextSelectFont (context, [self.font.fontName UTF8String], size, kCGEncodingMacRoman);
        CGContextSetCharacterSpacing (context, characterSpacing);
        CGContextSetTextDrawingMode (context, kCGTextFill);

        // Rotate text to not be upside down
        CGAffineTransform xform = CGAffineTransformMake(1.0, 0.0, 0.0, -1.0, 0.0, 0.0);
        CGContextSetTextMatrix(context, xform);
        const char *cStr = [self.text UTF8String];
        CGContextShowTextAtPoint (context, rect.origin.x, rect.origin.y + size, cStr, strlen(cStr));
    }
    else
    {
        // no character spacing provided so do normal drawing
        [super drawTextInRect:rect];
    }
}

@end

然后使用它,只需在viewDidLoad中设置标签或其他东西

Then to use it, just set up the label in viewDidLoad or something

- (void)viewDidLoad
{
        myLabel.characterSpacing = 2; // point size
}

我尝试使用UITextField,但不幸的是它只添加了用户编辑字段后的字符间距。 -drawTextInRect仅在-textFieldShouldEndEditing委托方法之后调用。从其他论坛中有人建议这是因为UITextField需要知道字体的渲染才能显示光标。从来没有为这件作品找到解决方案...

I tried it with UITextField, but unfortunately it only adds the character spacing after the user has edited the field. -drawTextInRect is only called after the -textFieldShouldEndEditing delegate method. From other forums some suggested this was because UITextField needs to know the rendering of the font in order to display the cursor. Never found a solution for that piece...