summaryrefslogtreecommitdiff
path: root/chromium/ui/gfx/ios/NSString+CrStringDrawing.mm
blob: f7a684d51a1d3a98697ef258c6d53ec12d0a6c28 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#import "ui/gfx/ios/NSString+CrStringDrawing.h"

#include <stddef.h>

#include "base/logging.h"
#include "ui/gfx/ios/uikit_util.h"

@implementation NSString (CrStringDrawing)

- (CGRect)cr_boundingRectWithSize:(CGSize)size
                             font:(UIFont*)font {
  NSDictionary* attributes = font ? @{NSFontAttributeName: font} : @{};
  return [self boundingRectWithSize:size
                            options:NSStringDrawingUsesLineFragmentOrigin
                         attributes:attributes
                            context:nil];
}

- (CGSize)cr_boundingSizeWithSize:(CGSize)size
                             font:(UIFont*)font {
  return [self cr_boundingRectWithSize:size font:font].size;
}

- (CGSize)cr_pixelAlignedSizeWithFont:(UIFont*)font {
  DCHECK(font) << "|font| can not be nil; it is used as a NSDictionary value";
  NSDictionary* attributes = @{ NSFontAttributeName : font };
  return ui::AlignSizeToUpperPixel([self sizeWithAttributes:attributes]);
}

- (CGSize)cr_sizeWithFont:(UIFont*)font {
  if (!font)
    return CGSizeZero;
  NSDictionary* attributes = @{ NSFontAttributeName : font };
  CGSize size = [self sizeWithAttributes:attributes];
  return CGSizeMake(ceil(size.width), ceil(size.height));
}

- (NSString*)cr_stringByCuttingToIndex:(NSUInteger)index {
  if (index == 0)
    return @"";
  if (index >= [self length])
    return [[self retain] autorelease];
  return [[self substringToIndex:(index - 1)] stringByAppendingString:@"…"];
}

- (NSString*)cr_stringByElidingToFitSize:(CGSize)bounds {
  CGSize sizeForGuess = CGSizeMake(bounds.width, CGFLOAT_MAX);
  // Use binary search on the string's length.
  size_t lo = 0;
  size_t hi = [self length];
  size_t guess = 0;
  for (guess = (lo + hi) / 2; lo < hi; guess = (lo + hi) / 2) {
    NSString* tempString = [self cr_stringByCuttingToIndex:guess];
    UIFont* font = [UIFont systemFontOfSize:[UIFont labelFontSize]];
    CGSize sizeGuess =
        [tempString cr_boundingSizeWithSize:sizeForGuess font:font];
    if (sizeGuess.height > bounds.height) {
      hi = guess - 1;
      if (hi < lo)
        hi = lo;
    } else {
      lo = guess + 1;
    }
  }
  return [self cr_stringByCuttingToIndex:lo];
}

@end