UIColor+FIRIAMHexString.m 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839
  1. /*
  2. * Copyright 2017 Google
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. #import "UIColor+FIRIAMHexString.h"
  17. @implementation UIColor (HexString)
  18. + (UIColor *)firiam_colorWithHexString:(nullable NSString *)hexString {
  19. if (hexString.length < 7) {
  20. return nil;
  21. }
  22. unsigned rgbValue = 0;
  23. NSScanner *scanner = [NSScanner scannerWithString:hexString];
  24. [scanner setScanLocation:1]; // bypass '#' character
  25. if (![scanner scanHexInt:&rgbValue]) {
  26. // no valid heximal value is detected
  27. return nil;
  28. }
  29. return [UIColor colorWithRed:((rgbValue & 0xFF0000) >> 16) / 255.0
  30. green:((rgbValue & 0xFF00) >> 8) / 255.0
  31. blue:(rgbValue & 0xFF) / 255.0
  32. alpha:1.0];
  33. }
  34. @end