RGB Color Gradation Function


/ Published in: Python
Save to your folder(s)



Copy this code and paste it in your HTML
  1. import string
  2.  
  3. def make_color_tuple( color ):
  4. """
  5. turn something like "#000000" into 0,0,0
  6. or "#FFFFFF into "255,255,255"
  7. """
  8. R = color[1:3]
  9. G = color[3:5]
  10. B = color[5:7]
  11.  
  12. R = int(R, 16)
  13. G = int(G, 16)
  14. B = int(B, 16)
  15.  
  16. return R,G,B
  17.  
  18. def interpolate_tuple( startcolor, goalcolor, steps ):
  19. """
  20. Take two RGB color sets and mix them over a specified number of steps. Return the list
  21. """
  22. # white
  23.  
  24. R = startcolor[0]
  25. G = startcolor[1]
  26. B = startcolor[2]
  27.  
  28. targetR = goalcolor[0]
  29. targetG = goalcolor[1]
  30. targetB = goalcolor[2]
  31.  
  32. DiffR = targetR - R
  33. DiffG = targetG - G
  34. DiffB = targetB - B
  35.  
  36. buffer = []
  37.  
  38. for i in range(0, steps +1):
  39. iR = R + (DiffR * i / steps)
  40. iG = G + (DiffG * i / steps)
  41. iB = B + (DiffB * i / steps)
  42.  
  43. hR = string.replace(hex(iR), "0x", "")
  44. hG = string.replace(hex(iG), "0x", "")
  45. hB = string.replace(hex(iB), "0x", "")
  46.  
  47. if len(hR) == 1:
  48. hR = "0" + hR
  49. if len(hB) == 1:
  50. hB = "0" + hB
  51.  
  52. if len(hG) == 1:
  53. hG = "0" + hG
  54.  
  55. color = string.upper("#"+hR+hG+hB)
  56. buffer.append(color)
  57.  
  58. return buffer
  59.  
  60. def interpolate( startcolor, goalcolor, steps ):
  61. """
  62. wrapper for interpolate_tuple that accepts colors as html ("#CCCCC" and such)
  63. """
  64. start_tuple = make_color_tuple(startcolor)
  65. goal_tuple = make_color_tuple(goalcolor)
  66.  
  67. return interpolate_tuple(start_tuple, goal_tuple, steps)
  68.  
  69.  
  70.  
  71. def printchart(startcolor, endcolor, steps):
  72.  
  73. colors = interpolate(startcolor, endcolor, steps)
  74.  
  75. for color in colors:
  76. print color
  77.  
  78.  
  79. # Example... show us 16 values of gradation between these two colors
  80. printchart("#999933", "#6666FF", 16)

URL: http://www.elifulkerson.com/projects/rgb-color-gradation.php

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.