ADHcolor.swift 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. //
  2. // ADHcolor.swift
  3. // ADHTuanCan
  4. //
  5. // Created by 敖德亨 on 2023/9/27.
  6. //
  7. import Foundation
  8. import UIKit
  9. extension UIColor {
  10. class func RGBColor(red : CGFloat,green :CGFloat ,blue : CGFloat,alpha : CGFloat) ->UIColor{
  11. return UIColor(red: red, green: green, blue: blue, alpha: alpha)
  12. }
  13. class func color(hex:String)->UIColor{
  14. var cString = hex.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines).uppercased()
  15. if (cString.hasPrefix("#")) {
  16. let index = cString.index(cString.startIndex, offsetBy:1)
  17. cString = cString.substring(from: index)
  18. }
  19. if (cString.count != 6) {
  20. return UIColor.red
  21. }
  22. let rIndex = cString.index(cString.startIndex, offsetBy: 2)
  23. let rString = cString.substring(to: rIndex)
  24. let otherString = cString.substring(from: rIndex)
  25. let gIndex = otherString.index(otherString.startIndex, offsetBy: 2)
  26. let gString = otherString.substring(to: gIndex)
  27. let bIndex = cString.index(cString.endIndex, offsetBy: -2)
  28. let bString = cString.substring(from: bIndex)
  29. var r:CUnsignedInt = 0, g:CUnsignedInt = 0, b:CUnsignedInt = 0;
  30. Scanner(string: rString).scanHexInt32(&r)
  31. Scanner(string: gString).scanHexInt32(&g)
  32. Scanner(string: bString).scanHexInt32(&b)
  33. return UIColor(red: CGFloat(r) / 255.0, green: CGFloat(g) / 255.0, blue: CGFloat(b) / 255.0, alpha: CGFloat(1))
  34. }
  35. class func color(hex:String,alpha:CGFloat)->UIColor{
  36. var cString = hex.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines).uppercased()
  37. if (cString.hasPrefix("#")) {
  38. let index = cString.index(cString.startIndex, offsetBy:1)
  39. cString = cString.substring(from: index)
  40. }
  41. if (cString.count != 6) {
  42. return UIColor.red
  43. }
  44. let rIndex = cString.index(cString.startIndex, offsetBy: 2)
  45. let rString = cString.substring(to: rIndex)
  46. let otherString = cString.substring(from: rIndex)
  47. let gIndex = otherString.index(otherString.startIndex, offsetBy: 2)
  48. let gString = otherString.substring(to: gIndex)
  49. let bIndex = cString.index(cString.endIndex, offsetBy: -2)
  50. let bString = cString.substring(from: bIndex)
  51. var r:CUnsignedInt = 0, g:CUnsignedInt = 0, b:CUnsignedInt = 0;
  52. Scanner(string: rString).scanHexInt32(&r)
  53. Scanner(string: gString).scanHexInt32(&g)
  54. Scanner(string: bString).scanHexInt32(&b)
  55. return UIColor(red: CGFloat(r) / 255.0, green: CGFloat(g) / 255.0, blue: CGFloat(b) / 255.0, alpha: CGFloat(alpha))
  56. }
  57. }