Is it possible to alter the letter-spacing/kerning of a font with Cocoa Touch?

前端 未结 5 2290
感情败类
感情败类 2020-12-14 03:38

I\'ve been scouring the Internet for a while now for information on how one can alter the letter-spacing/kerning of a font within UIKit.

My fear is, that like using

5条回答
  •  隐瞒了意图╮
    2020-12-14 04:19

    The accepted answer lost a lot of the formatting, and user363349's answer mostly worked for me but text alignment wasn't working. I modified the code to fix that:

    - (void) drawRect:(CGRect)rect
    {
        // Drawing code
        CGContextRef context = UIGraphicsGetCurrentContext();
        CGContextSelectFont (context, [self.font.fontName cStringUsingEncoding:NSASCIIStringEncoding], self.font.pointSize, kCGEncodingMacRoman);
        CGContextSetCharacterSpacing(context, characterSpacing);
        CGContextSetFillColorWithColor(context, [[UIColor clearColor] CGColor]);
        CGAffineTransform myTextTransform = CGAffineTransformScale(CGAffineTransformIdentity, 1.f, -1.f );
    
        CGContextSetTextMatrix (context, myTextTransform);
    
        // draw 1 but invisbly to get the string length.
        CGPoint p =CGContextGetTextPosition(context);
        float centeredY = (self.font.pointSize + (self.frame.size.height- self.font.pointSize)/2)-2;
        CGContextShowTextAtPoint(context, 0, centeredY, [self.text cStringUsingEncoding:NSASCIIStringEncoding], [self.text length]);
        CGPoint v =CGContextGetTextPosition(context);
    
        // calculate width and draw second one.
        float width = v.x - p.x;
        float destX = 0;
    
        // calculate X position based on alignment
        if([self textAlignment] == UITextAlignmentLeft){
            destX = 0;
        }else if([self textAlignment] == UITextAlignmentCenter){
            destX = (self.frame.size.width- width)/2;
        }else if([self textAlignment] == UITextAlignmentRight){
            destX = self.frame.size.width - width;
        }
        CGContextSetFillColorWithColor(context, [self.textColor CGColor]);
        CGContextShowTextAtPoint(context, destX, centeredY, [self.text cStringUsingEncoding:NSASCIIStringEncoding], [self.text length]);
    }
    

提交回复
热议问题