NSString+CrStringDrawing.mm 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  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.
  4. #import "ui/gfx/ios/NSString+CrStringDrawing.h"
  5. #include <ostream>
  6. #include <stddef.h>
  7. #include "base/check.h"
  8. #include "ui/gfx/ios/uikit_util.h"
  9. @implementation NSString (CrStringDrawing)
  10. - (CGRect)cr_boundingRectWithSize:(CGSize)size
  11. font:(UIFont*)font {
  12. NSDictionary* attributes = font ? @{NSFontAttributeName: font} : @{};
  13. return [self boundingRectWithSize:size
  14. options:NSStringDrawingUsesLineFragmentOrigin
  15. attributes:attributes
  16. context:nil];
  17. }
  18. - (CGSize)cr_boundingSizeWithSize:(CGSize)size
  19. font:(UIFont*)font {
  20. return [self cr_boundingRectWithSize:size font:font].size;
  21. }
  22. - (CGSize)cr_pixelAlignedSizeWithFont:(UIFont*)font {
  23. DCHECK(font) << "|font| can not be nil; it is used as a NSDictionary value";
  24. NSDictionary* attributes = @{ NSFontAttributeName : font };
  25. return ui::AlignSizeToUpperPixel([self sizeWithAttributes:attributes]);
  26. }
  27. - (CGSize)cr_sizeWithFont:(UIFont*)font {
  28. if (!font)
  29. return CGSizeZero;
  30. NSDictionary* attributes = @{ NSFontAttributeName : font };
  31. CGSize size = [self sizeWithAttributes:attributes];
  32. return CGSizeMake(ceil(size.width), ceil(size.height));
  33. }
  34. - (NSString*)cr_stringByCuttingToIndex:(NSUInteger)index {
  35. if (index == 0)
  36. return @"";
  37. if (index >= [self length])
  38. return [[self retain] autorelease];
  39. return [[self substringToIndex:(index - 1)] stringByAppendingString:@"…"];
  40. }
  41. - (NSString*)cr_stringByElidingToFitSize:(CGSize)bounds {
  42. CGSize sizeForGuess = CGSizeMake(bounds.width, CGFLOAT_MAX);
  43. // Use binary search on the string's length.
  44. size_t lo = 0;
  45. size_t hi = [self length];
  46. size_t guess = 0;
  47. for (guess = (lo + hi) / 2; lo < hi; guess = (lo + hi) / 2) {
  48. NSString* tempString = [self cr_stringByCuttingToIndex:guess];
  49. UIFont* font = [UIFont systemFontOfSize:[UIFont labelFontSize]];
  50. CGSize sizeGuess =
  51. [tempString cr_boundingSizeWithSize:sizeForGuess font:font];
  52. if (sizeGuess.height > bounds.height) {
  53. hi = guess - 1;
  54. if (hi < lo)
  55. hi = lo;
  56. } else {
  57. lo = guess + 1;
  58. }
  59. }
  60. return [self cr_stringByCuttingToIndex:lo];
  61. }
  62. @end