If I try to find out the width in pixels for a string
CGSize sz = [@"Test text to hilight without new line for testing" sizeWithFont:CGTextLabel.font];
NSLog(NSStringFromCGSize(sz));
output is : CoregraphicsDrawing[3306:f803] {339, 21}
if i try separate the string by space @” “ and loop it to add width for each word + width for space after each word, total width is different
CoregraphicsDrawing[3306:f803] 351.000000
please check this code where I am calculating width word by word:
str = @"Test text to hilight without new line for testing";
self.words = [NSMutableArray arrayWithArray:[str componentsSeparatedByString:@" "]];
CGFloat pos = 0;
[self.rects addObject:[NSValue valueWithCGPoint:CGPointMake(0, 0)]];
for(int i = 0; i < [self.words count]; i++)
{
NSString *w = [self.words objectAtIndex:i];
NSLog(w);
CGSize sz = [w sizeWithFont:CGTextLabel.font];
pos += sz.width;
pos += [@" " sizeWithFont:CGTextLabel.font].width;
if(i != [self.words count]-1)
{
[self.rects addObject:[NSValue valueWithCGPoint:CGPointMake(pos, 0)]];
}
else {
NSLog(@"%f",pos); //here actual calculated width is printed.
}
}
If anyone could suggest a solution, I would be really thankful.
After doing some testing, it looks like calling
sizeWithFont:with just a space, adds extra room and does not treat it the same as a space between characters. This is what was happening when I tried to usesystemFont.So everytime you use
[@" " sizeWithFont:CGTextLabel.font].width;you are not going to get the size of a space between characters, but most likely some extra bits on the ends as well. I noticed this using the following:I got this returned from the console:
So the space alone is returning 4 “pixels” of width. “Hello” is returning 28, “There” is returning 32. So together you would tink it is 64, but I got 63. So the space is taking up 3 there instead of 4. Likewise, when I did “Hello There Hello There” you would think I would get 63*2 + 4 for the space = 130. Instead I got 63*2 + 2. So the space in this case is really only taking up 2-3 “pixels” most of the time but if I call
sizeWithFont:for just a@" "I get 4.Fonts do not always create the exact same amount of gap for every space, and that is probably why you are having your issue. Through my testing I got the space as adding 2, 3, or even 4 “pixels” to different combinations of words. I think this call should only be used if you have the whole phrase, it is too difficult to try and add it all together. Is there another method to create the functionality you are looking for?
Edit: I also found that just taking two words and putting them together will give you differing results from taking them individually:
returned 59, when “Hello” returned 28 and “There” returned 32.