c# 颜色RGB到HSB互相转换
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了c# 颜色RGB到HSB互相转换相关的知识,希望对你有一定的参考价值。
1 /// <summary> 2 /// 色相,饱和度,亮度转换成rgb值 3 /// </summary> 4 /// <returns></returns> 5 public static float[] HSB2RGB(float[] hsb) 6 { 7 if (hsb[0] == 360) 8 { 9 hsb[0] = 0; 10 } 11 float[] rgb = new float[3]; 12 float r = 0; 13 float g = 0; 14 float b = 0; 15 16 if (hsb[1] == 0) 17 { 18 r = g = b = hsb[2]; 19 } 20 else 21 { 22 float sectorPos = hsb[0] / 60f; 23 int sectorNum = (int)Math.Floor(sectorPos); 24 float fractionalSector = sectorPos - sectorNum; 25 float p = hsb[2] * (1 - hsb[1]); 26 float q = hsb[2] * (1 - (hsb[1] * fractionalSector)); 27 float t = hsb[2] * (1 - (hsb[1] * (1 - fractionalSector))); 28 switch (sectorNum) 29 { 30 case 0: 31 r = hsb[2]; 32 g = t; 33 b = p; 34 break; 35 case 1: 36 r = q; 37 g = hsb[2]; 38 b = p; 39 break; 40 case 2: 41 r = p; 42 g = hsb[2]; 43 b = t; 44 break; 45 case 3: 46 r = p; 47 g = q; 48 b = hsb[2]; 49 break; 50 case 4: 51 r = t; 52 g = p; 53 b = hsb[2]; 54 break; 55 case 5: 56 r = hsb[2]; 57 g = p; 58 b = q; 59 break; 60 } 61 62 } 63 return new float[] { r * 255, g * 255, b * 255 }; 64 } 65 /// <summary> 66 /// 将rgb类型的颜色转换为hsb 67 /// </summary> 68 /// <param name="rgb"></param> 69 /// <returns></returns> 70 public static float[] RGB2HSB(float[] rgb) 71 { 72 float[] hsb = new float[3]; 73 float r = rgb[0]; 74 float g = rgb[1]; 75 float b = rgb[2]; 76 77 float max = Math.Max(r, Math.Max(g, b)); 78 if (max <= 0) 79 { 80 return hsb; 81 } 82 float min = Math.Min(r, Math.Min(g, b)); 83 float dif = max - min; 84 if (max > min) 85 { 86 if (g == max) 87 { 88 hsb[0] = (b - r) / dif * 60f + 120f; 89 } 90 else if (b == max) 91 { 92 hsb[0] = (r - g) / dif * 60f + 240f; 93 } 94 else if (b > g) 95 { 96 hsb[0] = (g - b) / dif * 60f + 360f; 97 } 98 else 99 { 100 hsb[0] = (g - b) / dif * 60f; 101 } 102 if (hsb[0] < 0) 103 { 104 hsb[0] = hsb[0] + 360f; 105 } 106 } 107 else 108 { 109 hsb[0] = 0; 110 } 111 hsb[1] = dif / max; 112 hsb[2] = max / 255f; 113 return hsb; 114 }
以上是关于c# 颜色RGB到HSB互相转换的主要内容,如果未能解决你的问题,请参考以下文章
ActionScript 3 AS3 RGB颜色(对象)到HSB颜色(对象)