Measuring the pixel width of a string

后端 未结 3 661
猫巷女王i
猫巷女王i 2020-11-29 05:45

I need to measure the pixel width of a string in Cocoa Touch. Can anyone point me to a link that explains how to do this?

相关标签:
3条回答
  • 2020-11-29 06:00

    On iPhone OS it is slightly different, instead look at the NSString UIKit Additions Reference. The idea is the same as in Cocoa for Mac OS X, but there are more methods.

    For single lines of text use:

    - (CGSize)sizeWithFont:(UIFont *)font 
                  forWidth:(CGFloat)width 
             lineBreakMode:(UILineBreakMode)lineBreakMode
    

    And for multiline texts use:

    - (CGSize)sizeWithFont:(UIFont *)font 
         constrainedToSize:(CGSize)size 
             lineBreakMode:(UILineBreakMode)lineBreakMode
    

    The use of a UILineBreakMode as argument for single lines of text can be confusing, but this is because the line break is also used to define how to truncate the text.

    0 讨论(0)
  • 2020-11-29 06:08

    Take a look at the NSString Application Kit Additions Reference, specifically boundingRectWithSize:options:attributes:. The value returned by that routine should give you the width of your NSString.

    0 讨论(0)
  • 2020-11-29 06:13

    The above solution is now deprecated. Check this for iOS 7+

     sizeWithFont:constrainedToSize:lineBreakMode 
    

    is deprecated now. Use below code snippet,

    UIFont *font=[UIFont fontWithName:@"Arial" size:16.f];
    
    NSString *name = @"APPLE";
    
    CGSize size = [name sizeWithAttributes:@{NSFontAttributeName:font}];
    
    0 讨论(0)
提交回复
热议问题