1 // Copyright 2014 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #import "ui/gfx/ios/NSString+CrStringDrawing.h"
7 #include "base/logging.h"
8 #include "ui/gfx/ios/uikit_util.h"
10 @implementation NSString (CrStringDrawing)
12 - (CGRect)cr_boundingRectWithSize:(CGSize)size
14 NSDictionary* attributes = font ? @{NSFontAttributeName: font} : @{};
15 return [self boundingRectWithSize:size
16 options:NSStringDrawingUsesLineFragmentOrigin
21 - (CGSize)cr_boundingSizeWithSize:(CGSize)size
23 return [self cr_boundingRectWithSize:size font:font].size;
26 - (CGSize)cr_pixelAlignedSizeWithFont:(UIFont*)font {
27 DCHECK(font) << "|font| can not be nil; it is used as a NSDictionary value";
28 NSDictionary* attributes = @{ NSFontAttributeName : font };
29 return ui::AlignSizeToUpperPixel([self sizeWithAttributes:attributes]);
32 - (CGSize)cr_sizeWithFont:(UIFont*)font {
35 NSDictionary* attributes = @{ NSFontAttributeName : font };
36 CGSize size = [self sizeWithAttributes:attributes];
37 return CGSizeMake(ceil(size.width), ceil(size.height));
40 - (NSString*)cr_stringByCuttingToIndex:(NSUInteger)index {
43 if (index >= [self length])
44 return [[self retain] autorelease];
45 return [[self substringToIndex:(index - 1)] stringByAppendingString:@"…"];
48 - (NSString*)cr_stringByElidingToFitSize:(CGSize)bounds {
49 CGSize sizeForGuess = CGSizeMake(bounds.width, CGFLOAT_MAX);
50 // Use binary search on the string's length.
52 size_t hi = [self length];
54 for (guess = (lo + hi) / 2; lo < hi; guess = (lo + hi) / 2) {
55 NSString* tempString = [self cr_stringByCuttingToIndex:guess];
56 UIFont* font = [UIFont systemFontOfSize:[UIFont labelFontSize]];
58 [tempString cr_boundingSizeWithSize:sizeForGuess font:font];
59 if (sizeGuess.height > bounds.height) {
67 return [self cr_stringByCuttingToIndex:lo];