How to change an UILabel/UIFont's letter spacing?

后端 未结 5 1387
小蘑菇
小蘑菇 2020-12-02 12:32

I\'ve searched loads already and couldn\'t find an answer.

I have a normal UILabel, defined this way:

    UILabel *totalColors = [[[UILabel alloc] in         


        
5条回答
  •  悲哀的现实
    2020-12-02 12:58

    I've extended UILabel to change the character spacing. This should work out the box and pulls font, text, color etc from the UILabel itself (proper coding!).

    You may notice I draw the text twice, first with clear color. This is to auto center the text in the label. Whilst this may be inefficient - isn't it nice to be auto centered?

    Enjoy!

    @interface RALabel : UILabel {
    }
    @end  
    
    @implementation RALabel 
    
    - (void) drawRect:(CGRect)rect 
    {
    
        // Drawing code
    
        CGContextRef context = UIGraphicsGetCurrentContext();
        CGContextSelectFont (context, [self.font.fontName cStringUsingEncoding:NSASCIIStringEncoding], self.font.pointSize, kCGEncodingMacRoman);
        CGContextSetCharacterSpacing(context, 1);
        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 centeredX =(self.frame.size.width- width)/2;
        CGContextSetFillColorWithColor(context, [self.textColor CGColor]);
        CGContextShowTextAtPoint(context, centeredX, centeredY, [self.text cStringUsingEncoding:NSASCIIStringEncoding], [self.text length]);
    
    }
    

提交回复
热议问题