JSBadgeView.m 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429
  1. /*
  2. Copyright (c) 2013 Javier Soto.
  3. Permission is hereby granted, free of charge, to any person obtaining a copy
  4. of this software and associated documentation files (the "Software"), to deal
  5. in the Software without restriction, including without limitation the rights
  6. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  7. copies of the Software, and to permit persons to whom the Software is
  8. furnished to do so, subject to the following conditions:
  9. The above copyright notice and this permission notice shall be included in
  10. all copies or substantial portions of the Software.
  11. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  12. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  13. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  14. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  15. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  16. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  17. THE SOFTWARE.
  18. */
  19. #import "JSBadgeView.h"
  20. #import <QuartzCore/QuartzCore.h>
  21. #include <mach-o/dyld.h>
  22. #if !__has_feature(objc_arc)
  23. #error JSBadgeView must be compiled with ARC.
  24. #endif
  25. // Silencing some deprecation warnings if your deployment target is iOS7 that can only be fixed by using methods that
  26. // Are only available on iOS7.
  27. // Soon JSBadgeView will require iOS 7 and we'll be able to use the new methods.
  28. #if __IPHONE_OS_VERSION_MIN_REQUIRED >= __IPHONE_7_0
  29. #define JSBadgeViewSilenceDeprecatedMethodStart() _Pragma("clang diagnostic push") \
  30. _Pragma("clang diagnostic ignored \"-Wdeprecated-declarations\"")
  31. #define JSBadgeViewSilenceDeprecatedMethodEnd() _Pragma("clang diagnostic pop")
  32. #else
  33. #define JSBadgeViewSilenceDeprecatedMethodStart()
  34. #define JSBadgeViewSilenceDeprecatedMethodEnd()
  35. #endif
  36. static const CGFloat JSBadgeViewShadowRadius = 0.0f;
  37. static const CGFloat JSBadgeViewHeight = 15.0f;
  38. static const CGFloat JSBadgeViewTextSideMargin = 5.0f;
  39. static const CGFloat JSBadgeViewCornerRadius = 7.5f;
  40. // Thanks to Peter Steinberger: https://gist.github.com/steipete/6526860
  41. static BOOL JSBadgeViewIsUIKitFlatMode(void)
  42. {
  43. static BOOL isUIKitFlatMode = NO;
  44. static dispatch_once_t onceToken;
  45. dispatch_once(&onceToken, ^{
  46. #ifndef kCFCoreFoundationVersionNumber_iOS_7_0
  47. #define kCFCoreFoundationVersionNumber_iOS_7_0 847.2
  48. #endif
  49. #ifndef UIKitVersionNumber_iOS_7_0
  50. #define UIKitVersionNumber_iOS_7_0 0xB57
  51. #endif
  52. // We get the modern UIKit if system is running >= iOS 7 and we were linked with >= SDK 7.
  53. if (kCFCoreFoundationVersionNumber >= kCFCoreFoundationVersionNumber_iOS_7_0) {
  54. isUIKitFlatMode = (NSVersionOfLinkTimeLibrary("UIKit") >> 16) >= UIKitVersionNumber_iOS_7_0;
  55. }
  56. });
  57. return isUIKitFlatMode;
  58. }
  59. @implementation JSBadgeView
  60. + (void)applyCommonStyle
  61. {
  62. JSBadgeView *badgeViewAppearanceProxy = JSBadgeView.appearance;
  63. badgeViewAppearanceProxy.backgroundColor = UIColor.clearColor;
  64. badgeViewAppearanceProxy.badgeAlignment = JSBadgeViewAlignmentTopRight;
  65. badgeViewAppearanceProxy.badgeBackgroundColor = UIColor.redColor;
  66. badgeViewAppearanceProxy.badgeTextFont = [UIFont boldSystemFontOfSize:9];
  67. badgeViewAppearanceProxy.badgeTextColor = UIColor.whiteColor;
  68. }
  69. + (void)applyLegacyStyle
  70. {
  71. JSBadgeView *badgeViewAppearanceProxy = JSBadgeView.appearance;
  72. badgeViewAppearanceProxy.badgeOverlayColor = [UIColor colorWithWhite:1.0f alpha:0.3];
  73. badgeViewAppearanceProxy.badgeTextShadowColor = UIColor.clearColor;
  74. badgeViewAppearanceProxy.badgeShadowColor = [UIColor colorWithWhite:0.0f alpha:0.4f];
  75. badgeViewAppearanceProxy.badgeShadowSize = CGSizeMake(0.0f, 3.0f);
  76. badgeViewAppearanceProxy.badgeStrokeWidth = 2.0f;
  77. badgeViewAppearanceProxy.badgeStrokeColor = UIColor.whiteColor;
  78. }
  79. + (void)applyIOS7Style
  80. {
  81. JSBadgeView *badgeViewAppearanceProxy = JSBadgeView.appearance;
  82. badgeViewAppearanceProxy.badgeOverlayColor = UIColor.clearColor;
  83. badgeViewAppearanceProxy.badgeTextShadowColor = UIColor.clearColor;
  84. badgeViewAppearanceProxy.badgeShadowColor = UIColor.clearColor;
  85. badgeViewAppearanceProxy.badgeStrokeWidth = 0.0f;
  86. badgeViewAppearanceProxy.badgeStrokeColor = badgeViewAppearanceProxy.badgeBackgroundColor;
  87. }
  88. + (void)initialize
  89. {
  90. if (self == JSBadgeView.class)
  91. {
  92. [self applyCommonStyle];
  93. if (JSBadgeViewIsUIKitFlatMode())
  94. {
  95. [self applyIOS7Style];
  96. }
  97. else
  98. {
  99. [self applyLegacyStyle];
  100. }
  101. }
  102. }
  103. - (id)initWithParentView:(UIView *)parentView alignment:(JSBadgeViewAlignment)alignment
  104. {
  105. if ((self = [self initWithFrame:CGRectZero]))
  106. {
  107. self.badgeAlignment = alignment;
  108. [parentView addSubview:self];
  109. }
  110. return self;
  111. }
  112. #pragma mark - Layout
  113. - (CGFloat)marginToDrawInside
  114. {
  115. return self.badgeStrokeWidth * 2.0f;
  116. }
  117. - (void)layoutSubviews
  118. {
  119. [super layoutSubviews];
  120. self.userInteractionEnabled = NO;
  121. CGRect newFrame = self.frame;
  122. const CGRect superviewBounds = CGRectIsEmpty(_frameToPositionInRelationWith) ? self.superview.bounds : _frameToPositionInRelationWith;
  123. const CGFloat textWidth = [self sizeOfTextForCurrentSettings].width;
  124. const CGFloat marginToDrawInside = [self marginToDrawInside];
  125. const CGFloat viewWidth = MAX(_badgeMinWidth, textWidth + JSBadgeViewTextSideMargin + (marginToDrawInside * 2));
  126. const CGFloat viewHeight = JSBadgeViewHeight + (marginToDrawInside * 2);
  127. const CGFloat superviewWidth = superviewBounds.size.width;
  128. const CGFloat superviewHeight = superviewBounds.size.height;
  129. newFrame.size.width = MAX(viewWidth, viewHeight);
  130. newFrame.size.height = viewHeight;
  131. switch (self.badgeAlignment) {
  132. case JSBadgeViewAlignmentTopLeft:
  133. newFrame.origin.x = -viewWidth / 2.0f;
  134. newFrame.origin.y = -viewHeight / 2.0f;
  135. break;
  136. case JSBadgeViewAlignmentTopRight:
  137. newFrame.origin.x = superviewWidth - (viewWidth / 2.0f);
  138. newFrame.origin.y = -viewHeight / 2.0f;
  139. break;
  140. case JSBadgeViewAlignmentTopCenter:
  141. newFrame.origin.x = (superviewWidth - viewWidth) / 2.0f;
  142. newFrame.origin.y = -viewHeight / 2.0f;
  143. break;
  144. case JSBadgeViewAlignmentCenterLeft:
  145. newFrame.origin.x = -viewWidth / 2.0f;
  146. newFrame.origin.y = (superviewHeight - viewHeight) / 2.0f;
  147. break;
  148. case JSBadgeViewAlignmentCenterRight:
  149. newFrame.origin.x = superviewWidth - (viewWidth / 2.0f);
  150. newFrame.origin.y = (superviewHeight - viewHeight) / 2.0f;
  151. break;
  152. case JSBadgeViewAlignmentBottomLeft:
  153. newFrame.origin.x = -viewWidth / 2.0f;
  154. newFrame.origin.y = superviewHeight - (viewHeight / 2.0f);
  155. break;
  156. case JSBadgeViewAlignmentBottomRight:
  157. newFrame.origin.x = superviewWidth - (viewWidth / 2.0f);
  158. newFrame.origin.y = superviewHeight - (viewHeight / 2.0f);
  159. break;
  160. case JSBadgeViewAlignmentBottomCenter:
  161. newFrame.origin.x = (superviewWidth - viewWidth) / 2.0f;
  162. newFrame.origin.y = superviewHeight - (viewHeight / 2.0f);
  163. break;
  164. case JSBadgeViewAlignmentCenter:
  165. newFrame.origin.x = (superviewWidth - viewWidth) / 2.0f;
  166. newFrame.origin.y = (superviewHeight - viewHeight) / 2.0f;
  167. break;
  168. default:
  169. NSAssert(NO, @"Unimplemented JSBadgeAligment type %lul", (unsigned long)self.badgeAlignment);
  170. }
  171. newFrame.origin.x += _badgePositionAdjustment.x;
  172. newFrame.origin.y += _badgePositionAdjustment.y;
  173. // Do not set frame directly so we do not interfere with any potential transform set on the view.
  174. self.bounds = CGRectIntegral(CGRectMake(0, 0, CGRectGetWidth(newFrame), CGRectGetHeight(newFrame)));
  175. self.center = CGPointMake(ceilf(CGRectGetMidX(newFrame)), ceilf(CGRectGetMidY(newFrame)));
  176. [self setNeedsDisplay];
  177. }
  178. #pragma mark - Private
  179. - (CGSize)sizeOfTextForCurrentSettings
  180. {
  181. JSBadgeViewSilenceDeprecatedMethodStart();
  182. return [self.badgeText sizeWithFont:self.badgeTextFont];
  183. JSBadgeViewSilenceDeprecatedMethodEnd();
  184. }
  185. #pragma mark - Setters
  186. - (void)setBadgeAlignment:(JSBadgeViewAlignment)badgeAlignment
  187. {
  188. if (badgeAlignment != _badgeAlignment)
  189. {
  190. _badgeAlignment = badgeAlignment;
  191. [self setNeedsLayout];
  192. }
  193. }
  194. - (void)setBadgePositionAdjustment:(CGPoint)badgePositionAdjustment
  195. {
  196. _badgePositionAdjustment = badgePositionAdjustment;
  197. [self setNeedsLayout];
  198. }
  199. - (void)setBadgeText:(NSString *)badgeText
  200. {
  201. if (badgeText != _badgeText)
  202. {
  203. _badgeText = [badgeText copy];
  204. [self setNeedsLayout];
  205. }
  206. }
  207. - (void)setBadgeTextColor:(UIColor *)badgeTextColor
  208. {
  209. if (badgeTextColor != _badgeTextColor)
  210. {
  211. _badgeTextColor = badgeTextColor;
  212. [self setNeedsDisplay];
  213. }
  214. }
  215. - (void)setBadgeTextShadowColor:(UIColor *)badgeTextShadowColor
  216. {
  217. if (badgeTextShadowColor != _badgeTextShadowColor)
  218. {
  219. _badgeTextShadowColor = badgeTextShadowColor;
  220. [self setNeedsDisplay];
  221. }
  222. }
  223. - (void)setBadgeTextShadowOffset:(CGSize)badgeTextShadowOffset
  224. {
  225. _badgeTextShadowOffset = badgeTextShadowOffset;
  226. [self setNeedsDisplay];
  227. }
  228. - (void)setBadgeTextFont:(UIFont *)badgeTextFont
  229. {
  230. if (badgeTextFont != _badgeTextFont)
  231. {
  232. _badgeTextFont = badgeTextFont;
  233. [self setNeedsLayout];
  234. [self setNeedsDisplay];
  235. }
  236. }
  237. - (void)setBadgeBackgroundColor:(UIColor *)badgeBackgroundColor
  238. {
  239. if (badgeBackgroundColor != _badgeBackgroundColor)
  240. {
  241. _badgeBackgroundColor = badgeBackgroundColor;
  242. [self setNeedsDisplay];
  243. }
  244. }
  245. - (void)setBadgeStrokeWidth:(CGFloat)badgeStrokeWidth
  246. {
  247. if (badgeStrokeWidth != _badgeStrokeWidth)
  248. {
  249. _badgeStrokeWidth = badgeStrokeWidth;
  250. [self setNeedsLayout];
  251. [self setNeedsDisplay];
  252. }
  253. }
  254. - (void)setBadgeStrokeColor:(UIColor *)badgeStrokeColor
  255. {
  256. if (badgeStrokeColor != _badgeStrokeColor)
  257. {
  258. _badgeStrokeColor = badgeStrokeColor;
  259. [self setNeedsDisplay];
  260. }
  261. }
  262. - (void)setBadgeShadowColor:(UIColor *)badgeShadowColor
  263. {
  264. if (badgeShadowColor != _badgeShadowColor)
  265. {
  266. _badgeShadowColor = badgeShadowColor;
  267. [self setNeedsDisplay];
  268. }
  269. }
  270. - (void)setBadgeShadowSize:(CGSize)badgeShadowSize
  271. {
  272. if (!CGSizeEqualToSize(badgeShadowSize, _badgeShadowSize))
  273. {
  274. _badgeShadowSize = badgeShadowSize;
  275. [self setNeedsDisplay];
  276. }
  277. }
  278. #pragma mark - Drawing
  279. - (void)drawRect:(CGRect)rect
  280. {
  281. const BOOL anyTextToDraw = (self.badgeText.length > 0);
  282. if (anyTextToDraw)
  283. {
  284. CGContextRef ctx = UIGraphicsGetCurrentContext();
  285. const CGFloat marginToDrawInside = [self marginToDrawInside];
  286. const CGRect rectToDraw = CGRectInset(rect, marginToDrawInside, marginToDrawInside);
  287. UIBezierPath *borderPath = [UIBezierPath bezierPathWithRoundedRect:rectToDraw byRoundingCorners:(UIRectCorner)UIRectCornerAllCorners cornerRadii:CGSizeMake(JSBadgeViewCornerRadius, JSBadgeViewCornerRadius)];
  288. /* Background and shadow */
  289. CGContextSaveGState(ctx);
  290. {
  291. CGContextAddPath(ctx, borderPath.CGPath);
  292. CGContextSetFillColorWithColor(ctx, self.badgeBackgroundColor.CGColor);
  293. CGContextSetShadowWithColor(ctx, self.badgeShadowSize, JSBadgeViewShadowRadius, self.badgeShadowColor.CGColor);
  294. CGContextDrawPath(ctx, kCGPathFill);
  295. }
  296. CGContextRestoreGState(ctx);
  297. const BOOL colorForOverlayPresent = self.badgeOverlayColor && ![self.badgeOverlayColor isEqual:[UIColor clearColor]];
  298. if (colorForOverlayPresent)
  299. {
  300. /* Gradient overlay */
  301. CGContextSaveGState(ctx);
  302. {
  303. CGContextAddPath(ctx, borderPath.CGPath);
  304. CGContextClip(ctx);
  305. const CGFloat height = rectToDraw.size.height;
  306. const CGFloat width = rectToDraw.size.width;
  307. const CGRect rectForOverlayCircle = CGRectMake(rectToDraw.origin.x,
  308. rectToDraw.origin.y - ceilf(height * 0.5),
  309. width,
  310. height);
  311. CGContextAddEllipseInRect(ctx, rectForOverlayCircle);
  312. CGContextSetFillColorWithColor(ctx, self.badgeOverlayColor.CGColor);
  313. CGContextDrawPath(ctx, kCGPathFill);
  314. }
  315. CGContextRestoreGState(ctx);
  316. }
  317. /* Stroke */
  318. CGContextSaveGState(ctx);
  319. {
  320. CGContextAddPath(ctx, borderPath.CGPath);
  321. CGContextSetLineWidth(ctx, self.badgeStrokeWidth);
  322. CGContextSetStrokeColorWithColor(ctx, self.badgeStrokeColor.CGColor);
  323. CGContextDrawPath(ctx, kCGPathStroke);
  324. }
  325. CGContextRestoreGState(ctx);
  326. /* Text */
  327. CGContextSaveGState(ctx);
  328. {
  329. CGContextSetFillColorWithColor(ctx, self.badgeTextColor.CGColor);
  330. CGContextSetShadowWithColor(ctx, self.badgeTextShadowOffset, 1.0, self.badgeTextShadowColor.CGColor);
  331. CGRect textFrame = rectToDraw;
  332. const CGSize textSize = [self sizeOfTextForCurrentSettings];
  333. textFrame.size.height = textSize.height;
  334. textFrame.origin.y = rectToDraw.origin.y + floorf((rectToDraw.size.height - textFrame.size.height) / 2.0f);
  335. JSBadgeViewSilenceDeprecatedMethodStart();
  336. [self.badgeText drawInRect:textFrame
  337. withFont:self.badgeTextFont
  338. lineBreakMode:NSLineBreakByClipping
  339. alignment:NSTextAlignmentCenter];
  340. JSBadgeViewSilenceDeprecatedMethodEnd();
  341. }
  342. CGContextRestoreGState(ctx);
  343. }
  344. }
  345. @end