public bool IsOldStar(Color pixelColor) { return ((pixelColor.GetHue() >= 150) && (pixelColor.GetHue() <= 258) && (pixelColor.GetSaturation() >= 0.10) && (pixelColor.GetBrightness() <= 0.90)); }
private static String FormatColor(String format, Color arg) { if (String.IsNullOrWhiteSpace(format)) { return arg.ToString(); } var numberFormatInfo = new NumberFormatInfo { NumberDecimalDigits = 1, PercentDecimalDigits = 0, PercentNegativePattern = 1, PercentPositivePattern = 1 }; switch (format) { case "hex": { return String.Format(numberFormatInfo, "#{0:x2}{1:x2}{2:x2}", arg.R, arg.G, arg.B); } case "HEX": { return String.Format(numberFormatInfo, "#{0:X2}{1:X2}{2:X2}", arg.R, arg.G, arg.B); } case "rgb": { return String.Format(numberFormatInfo, "rgb({0}, {1}, {2})", arg.R, arg.G, arg.B); } case "rgb%": { return String.Format(numberFormatInfo, "rgb({0:P}, {1:P}, {2:P})", arg.R / 255d, arg.G / 255d, arg.B / 255d); } case "rgba": { return String.Format(numberFormatInfo, "rgba({0}, {1}, {2}, {3:0.#})", arg.R, arg.G, arg.B, arg.A / 255d); } case "rgba%": { return String.Format(numberFormatInfo, "rgba({0:P}, {1:P}, {2:P}, {3:0.#})", arg.R / 255d, arg.G / 255d, arg.B / 255d, arg.A / 255d); } case "hsl": { return String.Format(numberFormatInfo, "hsl({0:F0}, {1:P}, {2:P})", arg.GetHue(), arg.GetSaturation(), arg.GetBrightness()); } case "hsla": { return String.Format(numberFormatInfo, "hsla({0:F0}, {1:P}, {2:P}, {3:0.#})", arg.GetHue(), arg.GetSaturation(), arg.GetBrightness(), arg.A / 255d); } default: { throw new FormatException(String.Format("Invalid format specified: \"{0}\".", format)); } } }
/// <summary> /// Gets a cool Highlight brush for highlighting things /// </summary> /// <param name="box">The rectangle in the box</param> /// <param name="selectionHighlight">The color to use for the higlight</param> /// <returns></returns> public static Brush HighlightBrush(Rectangle box, Color selectionHighlight) { float med = selectionHighlight.GetBrightness(); float bright = med + 0.05f; if (bright > 1f) bright = 1f; float dark = med - 0.05f; if (dark < 0f) dark = 0f; Color brtCol = ColorFromHsl(selectionHighlight.GetHue(), selectionHighlight.GetSaturation(), bright); Color drkCol = ColorFromHsl(selectionHighlight.GetHue(), selectionHighlight.GetSaturation(), dark); return new LinearGradientBrush(box, brtCol, drkCol, LinearGradientMode.Vertical); }
private void getColour() { int r, g, b = 0; DialogResult result = GUI.colorDialog.ShowDialog(); if (result != DialogResult.Cancel) { color = GUI.colorDialog.Color; r = color.R; g = color.G; b = color.B; GUI.txtColourRGBdecimal.Text = r + ", " + g + ", " + b; GUI.txtColourRGB.Text = String.Format("{0:X2}", r) + String.Format("{0:X2}", g) + String.Format("{0:X2}", b); GUI.txtColourRGBcss.Text = "#" + String.Format("{0:X2}", r) + String.Format("{0:X2}", g) + String.Format("{0:X2}", b); GUI.txtColourRdec.Text = r.ToString(); GUI.txtColourGdec.Text = g.ToString(); GUI.txtColourBdec.Text = b.ToString(); GUI.txtColourRhex.Text = String.Format("{0:X2}", r); GUI.txtColourGhex.Text = String.Format("{0:X2}", g); GUI.txtColourBhex.Text = String.Format("{0:X2}", b); GUI.lblColourSample.BackColor = color; GUI.lblColourSample.Image = null; // RGB ->HSL conversion decimal h = decimal.Round(((decimal)(color.GetHue() / 360) * 240), MidpointRounding.AwayFromZero); decimal s = decimal.Round(((decimal)color.GetSaturation() * 240), MidpointRounding.AwayFromZero); decimal l = decimal.Round(((decimal)color.GetBrightness() * 240), MidpointRounding.AwayFromZero); GUI.txtColourH.Text = h.ToString(); GUI.txtColourS.Text = s.ToString(); GUI.txtColourL.Text = l.ToString(); } }
public HSLColor(Color color) { RGB = color; H = (byte)((color.GetHue() / 360.0f) * 255); S = (byte)(color.GetSaturation() * 255); L = (byte)(color.GetBrightness() * 255); }
private void Image_MouseMove(System.Windows.Controls.Image clickedImage, MouseEventArgs e) { int x = (int)(e.GetPosition(clickedImage).X); int y = (int)(e.GetPosition(clickedImage).Y); BitmapInfo[] bitmapInfos = new BitmapInfo[] { bitmapInfoSource, bitmapInfoFiltered }; System.Windows.Controls.Label[] labels = new System.Windows.Controls.Label[] { LabelColorSource, LabelColorFiltered }; LabelInfo.Content = String.Format("X={0:D4}, Y={1:D4}", x, y); for (int i = 0; i < 2; ++i) { if (bitmapInfos[i] == null) { continue; } System.Drawing.Color color = bitmapInfos[i].GetPixelColor(x, y); float hue = color.GetHue(); labels[i].Content = String.Format("A={0:D3}, R={1:D3}, G={2:D3}, B={3:D3}, H={4:###.##}", color.A, color.R, color.G, color.B, hue); } }
public static void GetColorComponents(ColorModel colorModel, Color color, out Single componentA, out Single componentB, out Single componentC) { componentA = 0.0f; componentB = 0.0f; componentC = 0.0f; switch (colorModel) { case ColorModel.RedGreenBlue: componentA = color.R; componentB = color.G; componentC = color.B; break; case ColorModel.HueSaturationBrightness: componentA = color.GetHue(); componentB = color.GetSaturation(); componentC = color.GetBrightness(); break; case ColorModel.LabColorSpace: RGBtoLab(color.R, color.G, color.B, out componentA, out componentB, out componentC); break; case ColorModel.XYZ: RGBtoXYZ(color.R, color.G, color.B, out componentA, out componentB, out componentC); break; } }
/// <summary> /// Initialize a new instance of the ColorHSL class. /// </summary> /// <param name="c">Initialize from an existing Color.</param> public ColorHSL(Color c) { // Initialize from the color instance _hue = c.GetHue() / 360f; _saturation = c.GetBrightness(); _luminance = c.GetSaturation(); }
/// <summary> /// returns the color that color.GetHue() is closest to (between red, green, yellow and blue) /// </summary> /// <param name="color"></param> /// <returns>closest color</returns> private int getColorCluster(System.Drawing.Color color) { int hue = (int)color.GetHue(); // An array holding hue distances from the color thresholds int[] hueDistances = new int[4]; int minIndex; int clusteredColorIndex; //Red hueDistances[0] = Math.Min(Math.Abs(RedHueThreshold - (hue)), Math.Abs(360 - (Math.Abs(RedHueThreshold - (hue))))); //Green hueDistances[1] = Math.Min(Math.Abs(GreenHueThreshold - (hue)), Math.Abs(360 - (Math.Abs(GreenHueThreshold - (hue))))); //Yellow hueDistances[2] = Math.Min(Math.Abs(YellowHueThreshold - (hue)), Math.Abs(360 - (Math.Abs(YellowHueThreshold - (hue))))); //Blue hueDistances[3] = Math.Min(Math.Abs(BlueHueThreshold - (hue)), Math.Abs(360 - (Math.Abs(BlueHueThreshold - (hue))))); minIndex = findMinIndex(hueDistances); if (_blackAndWhiteImageMode) { clusteredColorIndex = 1; // white and black can be represented by 1 and the brightness is the influencing factor whether it will be white or black } else { clusteredColorIndex = minIndex + 2; } // Color indices 0,1,2,3,4,5 for Black,White,Red,Green,Yellow,Blue respectively return(clusteredColorIndex); }
/// <summary> /// 获取主题色 /// </summary> /// <param name="bitmap"></param> /// <returns></returns> public static System.Windows.Media.Color GetThemeColor(this Bitmap bitmap) { System.Drawing.Color c = bitmap.GetMajorColor(); c = ColorHelper.FromAhsb(255, c.GetHue(), 0.6F, 0.7F); return(c.ToMedia()); }
public static ColorSlider Saturation(VisualDirection direction, float knobWidth, float minVisualLength, Color color, Reaction<float> changed) { return new ColorSlider (direction, knobWidth, minVisualLength, 0f, 1f, color.GetSaturation (), new [] { Color.White, VisualHelpers.ColorFromHSB (color.GetHue (), 1f, color.GetBrightness ()) }, changed); }
private static void UpdateAutoSelect() { Skybound.VisualTips.Rendering.VisualTipOfficePreset visualTipOfficePreset; System.Drawing.Color color1 = System.Drawing.SystemColors.ActiveCaption; float f = color1.GetHue(); if ((f >= 200.0F) && (f <= 250.0F)) { visualTipOfficePreset = Skybound.VisualTips.Rendering.VisualTipOfficePreset.XPBlue; } else if ((f >= 70.0F) && (f <= 120.0F)) { visualTipOfficePreset = Skybound.VisualTips.Rendering.VisualTipOfficePreset.XPGreen; } else { if (f != 0.0F) { System.Drawing.Color color2 = System.Drawing.SystemColors.ActiveCaption; if (color2.GetSaturation() >= 0.1F) { goto label_1; } } visualTipOfficePreset = Skybound.VisualTips.Rendering.VisualTipOfficePreset.XPSilver; goto label_2; label_1: visualTipOfficePreset = Skybound.VisualTips.Rendering.VisualTipOfficePreset.Control; } label_2: Skybound.VisualTips.Rendering.VisualTipOfficePreset._AutoSelect = (Skybound.VisualTips.Rendering.VisualTipOfficePreset)visualTipOfficePreset.MemberwiseClone(); }
public void RGBtoHSL(int R, int G, int B) { System.Drawing.Color HSL = System.Drawing.Color.FromArgb(R, G, B); i_HSL_H = HSL.GetHue(); i_HSL_S = HSL.GetSaturation(); i_HSL_L = HSL.GetBrightness(); }
public HslColor(Color color) { _alpha = color.A; _hue = color.GetHue(); _saturation = color.GetSaturation(); _lightness = color.GetBrightness(); _isEmpty = false; }
/// <summary> /// Uses the hue values from the specified start and end color to set the handle positions. /// </summary> /// <param name="startColor">The start color that represents the left hue</param> /// <param name="endColor">The start color that represents the right hue</param> public void SetRange(Color startColor, Color endColor) { int hStart = (int)startColor.GetHue(); int hEnd = (int)endColor.GetHue(); _inverted = (hStart > hEnd); LeftValue = hStart; RightValue = hEnd; }
private static double CalculateColorDifference(Color lhs, Color rhs) { double hue = lhs.GetHue() - rhs.GetHue(); double brightness = lhs.GetBrightness() - rhs.GetBrightness(); double saturation = lhs.GetSaturation() - rhs.GetSaturation(); return Math.Sqrt(hue * hue + brightness * brightness + saturation * saturation); }
private void ChangeColor(object sender, MouseButtonEventArgs e) { System.Windows.Point p = e.GetPosition(((IInputElement)e.Source)); if ((p.X >= 0) && (p.X < EditableImage.Width) && (p.Y >= 0) && (p.Y < EditableImage.Height)) { var bitmap = BitmapFromWriteableBitmap(EditableImage); System.Drawing.Color color = bitmap.GetPixel((int)p.X, (int)p.Y); var rr = -1; var gg = -1; var bb = -1; int r = 0; int g = 0; int b = 0; if (int.TryParse(R.Text, out rr) && rr >= 0 && rr < 256) { r = rr; } else { MessageBox.Show("Wrong Data"); } if (int.TryParse(R.Text, out gg) && gg >= 0 && gg < 256) { g = gg; } else { MessageBox.Show("Wrong Data"); } if (int.TryParse(R.Text, out bb) && bb >= 0 && bb < 256) { b = bb; } else { MessageBox.Show("Wrong Data"); } System.Drawing.Color colorToSet = System.Drawing.Color.FromArgb(r, g, b); float hue = color.GetHue(); float saturation = color.GetSaturation(); float brightness = color.GetBrightness(); bitmap = CreateNonIndexedImage(bitmap); bitmap.SetPixel(Convert.ToInt32(p.X), Convert.ToInt32(p.Y), colorToSet); EditableImage = WriteableBitmapBitmapFromBitmap(bitmap); Image.Source = EditableImage; } }
// Normalised so that h is 0..1, not 0..360 public static void ColorToHSV(Color color, out float hue, out float saturation, out float value) { int max = Math.Max(color.R, Math.Max(color.G, color.B)); int min = Math.Min(color.R, Math.Min(color.G, color.B)); hue = color.GetHue() / 360.0f; saturation = (float) (max == 0 ? 0 : 1d - 1d * min / max); value = (float) (max / 255d); }
/// <summary> /// Sets a given group of RGBW bulbs to the specified color's hue. Does not /// support Saturation and Luminosity/Brightness of the color. /// For a better representation of the color use <see cref="SetTrueColor"/>. /// </summary> /// <param name="group">1-4 or 0 for all groups.</param> /// <param name="color">The <see cref="System.Drawing.Color"/> to set.</param> public void SetColor(int group, Color color) { CheckGroup(group); // Check and select SelectGroup(group); var command = new [] { HUE, HueToMiLight(color.GetHue()), END }; Controller.SendCommand(command); }
protected virtual Color FinalizeColor(Color color) { // Since we use HSV to calculate there is no way to make a color 'brighter' than 100% // Be carefull with the naming: Since we use HSV the correct term is 'value' but outside we call it 'brightness' // THIS IS NOT A HSB CALCULATION!!! float finalBrightness = color.GetHSVValue() * (Brightness < 0 ? 0 : (Brightness > 1f ? 1f : Brightness)); byte finalAlpha = (byte)(color.A * (Opacity < 0 ? 0 : (Opacity > 1f ? 1f : Opacity))); return ColorHelper.ColorFromHSV(color.GetHue(), color.GetHSVSaturation(), finalBrightness, finalAlpha); }
private static void ColorToHSL(Color color, out double hue, out double saturation, out double lightness) { double M = Math.Max(color.R, Math.Max(color.G, color.B))/255.0d; double m = Math.Min(color.R, Math.Min(color.G, color.B))/255.0d; double C = M - m; hue = color.GetHue(); lightness = 0.5d*(M + m); saturation = (C == 0) ? 0 : (lightness <= 0.5 ? C/2*lightness : C/(2 - 2*lightness)); }
public static HSV ToHsv(this System.Drawing.Color c) { return(new HSV() { H = c.GetHue(), S = c.GetSaturation(), V = c.GetBrightness(), }); }
public static void RGBToHSV(Color color, out float H, out float S, out float V) { int max = Math.Max(color.R, Math.Max(color.G, color.B)); int min = Math.Min(color.R, Math.Min(color.G, color.B)); H = color.GetHue(); S = (max == 0) ? 0 : 1f - (1f * min / max); V = max / 255f; }
/// <summary> /// Initializes a new instance of the <see cref="DistinctColorInfo"/> struct. /// </summary> public DistinctColorInfo(Color color) { Color = color.ToArgb(); Count = 1; Hue = Convert.ToInt32(color.GetHue()*Factor); Saturation = Convert.ToInt32(color.GetSaturation()*Factor); Brightness = Convert.ToInt32(color.GetBrightness()*Factor); }
public static void ColorToHSV(Color color, out double hue, out double saturation, out double value) { int max = Math.Max(color.R, Math.Max(color.G, color.B)); int min = Math.Min(color.R, Math.Min(color.G, color.B)); hue = color.GetHue(); saturation = (max == 0) ? 0 : 1d - (1d * min / max); value = max / 255d; }
public static void ColorToHSV(Color color, out double hue, out double saturation, out double value) { int max = Math.Max(color.R, Math.Max(color.G, color.B)); int min = Math.Min(color.R, Math.Min(color.G, color.B)); hue = color.GetHue(); saturation = (max == 0) ? 0 : 1d - (1d * min / max); value = max / 255d; }
//********************************************************************************************************************************************************************************************** //********************************************************************************************************************************************************************************************** //********************************************************************************************************************************************************************************************** #region Image, Histogram utilities /// <summary> /// Convert RGB Color to HSV /// </summary> /// <param name="color">Color to convert</param> /// <param name="hue">Hue [0...179]</param> /// <param name="saturation">Saturation [0...255]</param> /// <param name="value">Value [0...255]</param> /// see: https://stackoverflow.com/questions/359612/how-to-change-rgb-color-to-hsv public static void ColorToHSV(System.Drawing.Color color, out double hue, out double saturation, out double value) { int max = Math.Max(color.R, Math.Max(color.G, color.B)); int min = Math.Min(color.R, Math.Min(color.G, color.B)); hue = color.GetHue() / 2; saturation = ((max == 0) ? 0 : 1d - (1d * min / max)) * 255; value = max; }
public static ColorSlider Hue(VisualDirection direction, float knobWidth, float minVisualLength, Color color, Reaction<float> changed) { return new ColorSlider (direction, knobWidth, minVisualLength, 0f, 1f, color.GetHue (), new [] { Color.Red, Color.Orange, Color.Yellow, Color.Green, Color.Blue, Color.Indigo, Color.Violet, Color.Red }, changed); }
public HSV(Color color) { int max = Math.Max(color.R, Math.Max(color.G, color.B)); int min = Math.Min(color.R, Math.Min(color.G, color.B)); this.Hue = color.GetHue(); this.Saturation = (max == 0) ? 0 : 1d - (1d * min / max); this.Value = max / 255d; }
public static System.Drawing.Color ModulateColor(System.Drawing.Color color, float mod) { float h = color.GetHue() / 360.0f; float s = color.GetSaturation(); float l = color.GetBrightness(); l += mod; l = Math.Min(l, 1.0f); double r = 0, g = 0, b = 0; double temp1, temp2; temp2 = ((l <= 0.5) ? l * (1.0 + s) : l + s - (l * s)); temp1 = 2.0 * l - temp2; double[] t3 = new double[] { h + 1.0 / 3.0, h, h - 1.0 / 3.0 }; double[] clr = new double[] { 0, 0, 0 }; for (int i = 0; i < 3; i++) { if (t3[i] < 0) { t3[i] += 1.0; } if (t3[i] > 1) { t3[i] -= 1.0; } if (6.0 * t3[i] < 1.0) { clr[i] = temp1 + (temp2 - temp1) * t3[i] * 6.0; } else if (2.0 * t3[i] < 1.0) { clr[i] = temp2; } else if (3.0 * t3[i] < 2.0) { clr[i] = (temp1 + (temp2 - temp1) * ((2.0 / 3.0) - t3[i]) * 6.0); } else { clr[i] = temp1; } } clr[0] = Math.Max(Math.Min(clr[0], 1.0), 0.0); clr[1] = Math.Max(Math.Min(clr[1], 1.0), 0.0); clr[2] = Math.Max(Math.Min(clr[2], 1.0), 0.0); r = clr[0] * 255.0; g = clr[1] * 255.0; b = clr[2] * 255.0; return(System.Drawing.Color.FromArgb(color.A, (int)r, (int)g, (int)b)); }
public void update(System.Drawing.Color c) { if (c == Color.Empty) { updateUI(string.Empty); return; } HSLString = c.GetHue().ToString("N2", CultureInfo.InvariantCulture) + ", " + c.GetSaturation().ToString("N2", CultureInfo.InvariantCulture) + ", " + c.GetBrightness().ToString("N2", CultureInfo.InvariantCulture); updateUI(HSLString); }
// /// <summary> /// Converts RGB to HSL /// </summary> /// <remarks>Takes advantage of whats already built in to .NET by using the Color.GetHue, Color.GetSaturation and Color.GetBrightness methods</remarks> /// <param name="c">A Color to convert</param> /// <returns>An HSL value</returns> public static HSL GetHSL(Color c) { HSL hsl = new HSL(); hsl.H = c.GetHue() / 360.0; // we store hue as 0-1 as opposed to 0-360 hsl.L = c.GetBrightness(); hsl.S = c.GetSaturation(); return hsl; }
public static Vector3 ColorToHSVDX11(this VRageMath.Color rgb) { System.Drawing.Color color = System.Drawing.Color.FromArgb(rgb.R, rgb.G, rgb.B); int num = Math.Max(color.R, Math.Max(color.G, color.B)); int num2 = Math.Min(color.R, Math.Min(color.G, color.B)); float x = color.GetHue() / 360f; float y = (num == 0) ? -1f : (1f - ((2f * num2) / ((float)num))); return(new Vector3(x, y, -1f + ((2f * num) / 255f))); }
int CompareColorByHue(Color c1, Color c2) { float h1 = c1.GetHue(); float h2 = c2.GetHue(); if (h1 < h2) return -1; if (h1 > h2) return 1; return 0; }
/// <summary> /// Constructor with ARGB color /// </summary> /// <param name="color">System.Drawing.Color value</param> public HSL(Color color) { try { this.HSLHelper(color.GetHue() / 360.0, color.GetSaturation(), color.GetBrightness()); } catch (Exception ee) { throw new GFXConversionException("HSL Constructor Error", ee); } }
// Original public static HSV ColorToHSV(Color color) { float max = Math.Max(color.R, Math.Max(color.G, color.B)); float min = Math.Min(color.R, Math.Min(color.G, color.B)); float hue = color.GetHue()/360; float saturation = ((float) max == 0) ? 0 : 1f - (1f*(float) min/(float) max); float value = max/255f; //Console.WriteLine("hue:" + hue); return new HSV(hue, saturation, value); }
public static HSV GetHSV(Color color) { HSV hsv = new HSV(); int max = Math.Max(color.R, Math.Max(color.G, color.B)); int min = Math.Min(color.R, Math.Min(color.G, color.B)); hsv.H = color.GetHue(); hsv.S = (max == 0) ? 0 : 1d - (1d * min / max); hsv.V = max / 255d; return hsv; }
public Tone GetTone(Color pixel) { float hue = pixel.GetHue(); float brightness = pixel.GetBrightness(); float saturation = pixel.GetSaturation(); var frequency = ConvertToFrequency(hue); var duration = ConvertToDuration(brightness); var volume = ConvertToVolume(saturation); //var duration = ConvertToDuration(saturation); //var volume = ConvertToVolume(brightness); return new Tone {Frequency = frequency, Duration = duration, Volume = volume}; }
public DialogResult ShowDlg(Color baseColor) { if(baseColor != null) { selHSLColor.Hue = baseColor.GetHue(); selHSLColor.Saturation = baseColor.GetSaturation(); selHSLColor.Lightness = baseColor.GetBrightness(); selHSLColor.Color = baseColor; lblFinalColorValue.BackColor = baseColor; } return ShowDialog(); }
public static void GetColorComponents(ColorModel colorModel, Color color, Color targetColor, out Single componentA, out Single componentB, out Single componentC) { componentA = 0.0f; componentB = 0.0f; componentC = 0.0f; switch (colorModel) { case ColorModel.RedGreenBlue: componentA = color.R - targetColor.R; componentB = color.G - targetColor.G; componentC = color.B - targetColor.B; break; case ColorModel.HueSaturationBrightness: componentA = color.GetHue() - targetColor.GetHue(); componentB = color.GetSaturation() - targetColor.GetSaturation(); componentC = color.GetBrightness() - targetColor.GetBrightness(); break; case ColorModel.LabColorSpace: Single sourceL, sourceA, sourceB; Single targetL, targetA, targetB; RGBtoLab(color.R, color.G, color.B, out sourceL, out sourceA, out sourceB); RGBtoLab(targetColor.R, targetColor.G, targetColor.B, out targetL, out targetA, out targetB); componentA = sourceL - targetL; componentB = sourceA - targetA; componentC = sourceB - targetB; break; case ColorModel.XYZ: Single sourceX, sourceY, sourceZ; Single targetX, targetY, targetZ; RGBtoXYZ(color.R, color.G, color.B, out sourceX, out sourceY, out sourceZ); RGBtoXYZ(targetColor.R, targetColor.G, targetColor.B, out targetX, out targetY, out targetZ); componentA = sourceX - targetX; componentB = sourceY - targetY; componentC = sourceZ - targetZ; break; } }
internal static ConsoleColor GetConsoleColor(Color color) { if (color.GetSaturation() < 0.5) { // we have a grayish color switch ((int)(color.GetBrightness()*3.5)) { case 0: return ConsoleColor.Black; case 1: return ConsoleColor.DarkGray; case 2: return ConsoleColor.Gray; default: return ConsoleColor.White; } } int hue = (int)Math.Round(color.GetHue()/60, MidpointRounding.AwayFromZero); if (color.GetBrightness() < 0.4) { // dark color switch (hue) { case 1: return ConsoleColor.DarkYellow; case 2: return ConsoleColor.DarkGreen; case 3: return ConsoleColor.DarkCyan; case 4: return ConsoleColor.DarkBlue; case 5: return ConsoleColor.DarkMagenta; default: return ConsoleColor.DarkRed; } } // bright color switch (hue) { case 1: return ConsoleColor.Yellow; case 2: return ConsoleColor.Green; case 3: return ConsoleColor.Cyan; case 4: return ConsoleColor.Blue; case 5: return ConsoleColor.Magenta; default: return ConsoleColor.Red; } }
private void MouseMove(object sender, MouseEventArgs e) { System.Windows.Point p = e.GetPosition(((IInputElement)e.Source)); if ((p.X >= 0) && (p.X < EditableImage.Width) && (p.Y >= 0) && (p.Y < EditableImage.Height)) { System.Drawing.Color color = BitmapFromWriteableBitmap(EditableImage).GetPixel((int)p.X, (int)p.Y); int r = color.R; int g = color.G; int b = color.B; float hue = color.GetHue(); float saturation = color.GetSaturation(); float brightness = color.GetBrightness(); RGB.Text = String.Format("R: {0} G: {1} B: {2}", r.ToString(), g.ToString(), b.ToString()); } }
public void MainColorCanvas_SelectedColorChanged(object sender, EventArgs e) { System.Windows.Media.Color mediaColor = (System.Windows.Media.Color)Main_ColorCanvas.SelectedColor; System.Drawing.Color drawingColor = System.Drawing.Color.FromArgb(mediaColor.A, mediaColor.R, mediaColor.G, mediaColor.B); HexCode_TextBox.Text = GetHex(drawingColor); HashCode_TextBox.Text = mediaColor.GetHashCode().ToString(); Brightness_TextBox.Text = (drawingColor.GetBrightness() * 100).ToString() + "%"; Saturation_TextBox.Text = (drawingColor.GetSaturation() * 100).ToString() + "%"; Hue_TextBox.Text = drawingColor.GetHue().ToString() + "°"; RP_TextBox.Text = (Math.Round(drawingColor.R / 256.0, 4) * 100).ToString() + "%"; GP_TextBox.Text = (Math.Round(drawingColor.G / 256.0, 4) * 100).ToString() + "%"; BP_TextBox.Text = (Math.Round(drawingColor.B / 256.0, 4) * 100).ToString() + "%"; RM_TextBox.Text = drawingColor.R.ToString(); GM_TextBox.Text = drawingColor.G.ToString(); BM_TextBox.Text = drawingColor.B.ToString(); }
/// <summary> /// Ccompares two colors by hue and returns an indication of their relative sort order. /// </summary> /// <param name="x">A color to compare to y.</param> /// <param name="y">A color to compare to x.</param> public static int Hue(Color x, Color y) { float v1; float v2; int result; v1 = x.GetHue(); v2 = y.GetHue(); if (v1 < v2) result = -1; else if (v1 > v2) result = 1; else result = 0; return result; }
// Event of changeing the text in the HexColorIO TextBox private void toolStripTextBoxHexColorIO_TextChanged(object sender, EventArgs e) { try { System.Drawing.Color rgbColor = System.Drawing.Color.White; rgbColor = ColorTranslator.FromHtml(((ToolStripTextBox)sender).Text); ((ToolStripTextBox)sender).BackColor = rgbColor; HSLColor hslColor = new HSLColor(240 - rgbColor.GetHue(), rgbColor.GetSaturation(), 240); ((ToolStripTextBox)sender).ForeColor = hslColor; string trimedHex = ((ToolStripTextBox)sender).Text.TrimStart('#'); if (trimedHex.Length >= 6) { SetPenumbraColors(true); } } catch { } }
private void update_square() { brush = new SolidBrush(Color.FromArgb(trackBar1.Value, trackBar2.Value, trackBar3.Value)); g.FillRectangle(brush, rect); label1.Text = "Red : " + trackBar1.Value.ToString(); label2.Text = "Green : " + trackBar2.Value.ToString(); label3.Text = "Blue : " + trackBar3.Value.ToString(); double c = 1 - ((double)trackBar1.Value / 255); double m = 1 - ((double)trackBar2.Value / 255); double k = 1 - ((double)trackBar3.Value / 255); label4.Text = "C: " + c.ToString() + "M: " + m.ToString() + "K: " + k.ToString(); System.Drawing.Color color = System.Drawing.Color.FromArgb(trackBar1.Value, trackBar2.Value, trackBar3.Value); float hue = color.GetHue(); float saturation = color.GetSaturation(); float lightness = color.GetBrightness(); label6.Text = "H: " + hue.ToString() + "S: " + saturation.ToString() + "V: " + lightness.ToString(); }
/// <summary> /// Used https://nl.wikipedia.org/wiki/HSV_(kleurruimte)#Omzetting_van_RGB_naar_HSV , edited it a bit. /// </summary> /// <param name="color">Input RGB color</param> /// <returns> Tuple with HSV values </returns> public static Tuple<double, double, double> ColorToHSV( Color color ) { //Our algorithm is a bit different from the wikipedia once, since our RGB values are between 0 and 255 instead of 0 and 1. int MaxColorValue = Math.Max( color.R, Math.Max( color.G, color.B ) ); int MinColorValue = Math.Min( color.R, Math.Min( color.G, color.B ) ); //Apparently, the Hue value of the color is already working. double Hue = color.GetHue( ); double Saturation; if ( MaxColorValue == 0 ) Saturation = 0; else Saturation = 1d - ( 1d * MinColorValue / MaxColorValue ); double Value = MaxColorValue / 255d; return new Tuple<double, double, double>( Hue, Saturation, Value ); }
public Gif Rainbow(Bitmap b, IMessage m) { Vector3[,] HSVimage = new Vector3[b.Width, b.Height]; int[,] Alphas = new int[b.Width, b.Height]; using (UnsafeBitmapContext c = ImageExtensions.CreateUnsafeContext(b)) for (int x = 0; x < b.Width; x++) { for (int y = 0; y < b.Height; y++) { Color col = c.GetPixel(x, y); Alphas[x, y] = col.A; HSVimage[x, y] = new Vector3(col.GetHue(), col.GetSaturation(), col.GetValue()); } } int steps = 20; int stepWidth = 360 / steps; Bitmap[] re = new Bitmap[steps]; for (int i = 0; i < steps; i++) { re[i] = new Bitmap(b.Width, b.Height); using UnsafeBitmapContext c = ImageExtensions.CreateUnsafeContext(re[i]); for (int x = 0; x < b.Width; x++) { for (int y = 0; y < b.Height; y++) { c.SetPixel(x, y, Color.FromArgb(Alphas[x, y], HSVimage[x, y].HsvToRgb())); HSVimage[x, y].X += stepWidth; while (HSVimage[x, y].X > 360) { HSVimage[x, y].X -= 360; } } } } return(new Gif(re, Enumerable.Repeat(33, re.Length).ToArray())); }
public CurrentCursorDetails GetPixelInfoAroundMousePosition(int OffsetX, int OffsetY) { Point cursor = new Point(); GetCursorPos(ref cursor); var bitmap = new Bitmap(OffsetX * 2, OffsetY * 2); var gfxScreenshot = Graphics.FromImage(bitmap); gfxScreenshot.CopyFromScreen(cursor.X - OffsetX, cursor.Y - OffsetY, cursor.X + OffsetX, cursor.Y - OffsetY, bitmap.Size); System.Drawing.Color col = CalculateAverageColor(bitmap); CurrentCursorDetails res = new CurrentCursorDetails { PosX = cursor.X, PosY = cursor.Y, Red = col.R, Green = col.G, Blue = col.B, Hue = col.GetHue(), Saturation = col.GetSaturation(), Brightness = col.GetBrightness() }; return(res); }
public void RGB2HSV(System.Drawing.Color RGB, ref int[] HSV) { // H:0-360, S;0-100, V;:0-100 //System.Drawing.Color MyColor = System.Drawing.Color.FromArgb(R, G, B); int B = RGB.B; int G = RGB.G; int R = RGB.R; HSV[0] = Convert.ToInt32(RGB.GetHue()); //奇怪——用微软自己的方法获得的S值和V值居然不对 //S=Convert.ToInt32(MyColor.GetSaturation()/255*100); //V=Convert.ToInt32(MyColor.GetBrightness()/255*100); decimal min; decimal max; decimal delta; decimal R1 = Convert.ToDecimal(R) / 255; decimal G1 = Convert.ToDecimal(G) / 255; decimal B1 = Convert.ToDecimal(B) / 255; min = Math.Min(Math.Min(R1, G1), B1); max = Math.Max(Math.Max(R1, G1), B1); HSV[2] = Convert.ToInt32(max * 100); delta = (max - min) * 100; if (max == 0 || delta == 0) { HSV[1] = 0; } else { HSV[1] = Convert.ToInt32(delta / max); } }
public async Task ColorCommand(int red, int green, int blue) { if (red > byte.MaxValue || red < byte.MinValue || green > byte.MaxValue || green < byte.MinValue || blue > byte.MaxValue || blue < byte.MinValue) { await SendErrorAsync("The red, green and blue values must be integers between 0 and 255."); return; } Color color = Color.FromArgb(red, green, blue); color.GetHsv(out float hue, out float saturation, out float value); var builder = new EmbedBuilder() .AddField("RGB", $"Red: **{color.R}**\nGreen: **{color.G}**\nBlue: **{color.B}**", true) .AddField("HSV", $"Hue: **{hue}**\nSaturation: **{saturation}**\nValue: **{value}**", true) .AddField("HSL", $"Hue: **{color.GetHue()}**\nSaturation: **{color.GetSaturation()}**\nLightness: **{color.GetBrightness()}**", true) .AddField("Hex Code", $"#{color.R:X2}{color.G:X2}{color.B:X2}"); await SendColorMessage(color, builder); }
public void Modify(Bitmap bitmap, double hueMin, double hueMax, float brightness, float contrast, float gamma, bool grayScale, System.Windows.Media.Color pixelColor, bool replaceGrayColor, bool imageEffects, List <ImageEffect> enabledFilters, List <ImageEffect> filters) { Bitmap modifiedBitmap = new Bitmap(bitmap); // Use "unsafe" because C# doesn't support pointer aritmetic by default unsafe { // Lock the bitmap into system memory // "PixelFormat" can be "Format24bppRgb", "Format32bppArgb", etc BitmapData bitmapData = modifiedBitmap.LockBits(new Rectangle(0, 0, modifiedBitmap.Width, modifiedBitmap.Height), ImageLockMode.ReadWrite, PixelFormat.Format32bppArgb); // Define variables for bytes per pixel, as well as Image Width & Height int bytesPerPixel = Image.GetPixelFormatSize(modifiedBitmap.PixelFormat) / 8; int heightInPixels = modifiedBitmap.Height; int widthInBytes = modifiedBitmap.Width * bytesPerPixel; // Define a pointer to the first pixel in the locked image // Scan0 gets or sets the address of the first pixel data in the bitmap // This can also be thought of as the first scan line in the bitmap byte *ptrFirstPixel = (byte *)bitmapData.Scan0; // Step thru each pixel in the image using pointers // Parallel.For execute a 'for' loop in which iterations may run in parallel Parallel.For(0, heightInPixels, y => { // Use the 'Stride' (scanline width) property to step line by line through the image byte *currentLine = ptrFirstPixel + (y * bitmapData.Stride); for (int x = 0; x < widthInBytes; x += bytesPerPixel) { // Get each pixel color (R, G & B) int oldBlue = currentLine[x]; int oldGreen = currentLine[x + 1]; int oldRed = currentLine[x + 2]; Color color = Color.FromArgb(oldRed, oldGreen, oldBlue); double hue = color.GetHue(); if (grayScale || hue < hueMin || hue > hueMax) { Color newColor; if (replaceGrayColor) { newColor = Color.FromArgb(pixelColor.A, pixelColor.R, pixelColor.G, pixelColor.B); } else { int avg = (oldRed + oldGreen + oldBlue) / 3; newColor = Color.FromArgb(avg, avg, avg); } // Change each pixels color currentLine[x] = newColor.B; currentLine[x + 1] = newColor.G; currentLine[x + 2] = newColor.R; currentLine[x + 3] = newColor.A; } } }); modifiedBitmap.UnlockBits(bitmapData); } if (imageEffects) { foreach (ImageEffect effect in enabledFilters) { if (effect.Filter.ToString().Contains("EdgeDetection")) { modifiedBitmap = EdgeDetection(modifiedBitmap, effect.Filter); } else if (effect.Filter.ToString().Contains("Emboss")) { modifiedBitmap = Emboss(modifiedBitmap, effect.Filter); } switch (effect.Filter) { case FilterType.Invert: InvertImage(modifiedBitmap); break; case FilterType.SepiaTone: SepiaTone(modifiedBitmap); break; case FilterType.Pixelate: modifiedBitmap = Pixelate(modifiedBitmap, effect.CurrentValue); break; case FilterType.Median: modifiedBitmap = MedianFilter(modifiedBitmap, effect.CurrentValue); break; case FilterType.BoxBlur: modifiedBitmap = BoxBlur(modifiedBitmap, effect.CurrentValue); break; case FilterType.GaussianBlur: modifiedBitmap = GaussianBlur(modifiedBitmap, effect.CurrentValue); break; default: break; } } } float[][] brightnessContrastArray = { new float[] { contrast, 0, 0, 0, 0 }, // scale red new float[] { 0, contrast, 0, 0, 0 }, // scale green new float[] { 0, 0, contrast, 0, 0 }, // scale blue new float[] { 0, 0, 0, 1, 0 }, // don't scale alpha new float[] { brightness, brightness, brightness, 0, 1 } }; ApplyColorMatrix(modifiedBitmap, brightnessContrastArray); SetGamma(modifiedBitmap, gamma); OnImageFinished(modifiedBitmap); }
private void FixedUpdate() { frameNum++; transform.position = Vector2.Lerp(start, dest, pullSpeed * frameNum); transform.eulerAngles = Vector3.zero; gameObject.transform.RotateAround(dest, new Vector3(0, 0, 1), lastRotation + rotationSpeed); lastRotation += rotationSpeed; #region Shooting bool doShoot = false; float shotOffset = AngleOffset; if (frameNum % 5 == 0) { switch (BulletType) { case SkeleBulletType.SANS: if (shotNum / 3 % 2 == 0) { BulletTag = "KunaiBlue"; doShoot = true; } break; case SkeleBulletType.PAPY: if (shotNum / 3 % 2 == 0) { BulletTag = "KunaiOrange"; doShoot = true; } break; case SkeleBulletType.UNDERFELL: if (shotNum % 8 > 1) { BulletTag = "Kunai"; if (shotNum % 3 == 0) { RainbowCol = GetCol(209, 36, 36); } else if (shotNum % 3 == 1) { RainbowCol = Color.grey; } else { RainbowCol = GetCol(255, 248, 117); } doShoot = true; } break; case SkeleBulletType.UNDERFRESH: if (shotNum % 8 > 3) { if (shotNum % 3 == 0) { BulletTag = "KunaiYellow"; } else if (shotNum % 3 == 1) { BulletTag = "KunaiPink"; } else { BulletTag = "KunaiPurple"; } doShoot = true; } break; case SkeleBulletType.DREAM: if (shotNum % 8 > 1) { BulletTag = "Kunai"; float r = Random.Range(0, 10); if (r < 5) { RainbowCol = GetCol(255, 252, 186); } else if (r < 8) { RainbowCol = GetCol(186, 255, 207); } else { RainbowCol = GetCol(186, 255, 249); } doShoot = true; } break; case SkeleBulletType.NIGHTMARE: if (shotNum % 2 == 0) { BulletTag = "Kunai"; float r = Random.Range(0, 10); if (r < 7) { RainbowCol = GetCol(107, 107, 107); } else { RainbowCol = GetCol(116, 248, 252); } doShoot = true; } break; case SkeleBulletType.UNDERVERSE: if (shotNum / 2 % 2 == 0) { BulletTag = "Kunai"; if (Random.Range(0, 2) == 0) { RainbowCol = Color.red; } else { RainbowCol = Color.white; } doShoot = true; } break; case SkeleBulletType.DUSTTALE: if (Random.Range(0, 7) != 0) { BulletTag = "Kunai"; RainbowCol = GetCol(214, 214, 186); int r = Random.Range(0, 6); if (r == 0) { RainbowCol = Color.red; } else if (r == 2) { RainbowCol = Color.blue; } shotOffset -= Random.Range(0f, 0.5f); doShoot = true; } break; case SkeleBulletType.HORRORTALE: if (shotNum % 5 != 0) { BulletTag = "Kunai"; if (Random.Range(0, 8) > 2) { RainbowCol = GetCol(69, 69, 69); } else { RainbowCol = GetCol(189, 72, 232); } shotOffset -= Random.Range(0, 10f); doShoot = true; } break; case SkeleBulletType.UNDERSWAP: if (shotNum / 5 % 2 == 0) { BulletTag = "Kunai"; RainbowCol = GetCol(100, 100, 100); if (Random.Range(0, 10) > 7) { RainbowCol = GetCol(255, 192, 66); } shotOffset -= Random.Range(0f, 1f); doShoot = true; } break; case SkeleBulletType.PIRATE: if (Mathf.Sin(shotNum) > -0.75f) { BulletTag = "Kunai"; if (Mathf.Sin(shotNum) > 0.75f) { RainbowCol = GetCol(54, 255, 171); } else { RainbowCol = GetCol(103, 181, 207); } shotOffset += -5 * Mathf.Sin(shotNum); doShoot = true; } break; case SkeleBulletType.OUTERTALE: if (shotNum / 3 % 2 == 0) { BulletTag = "Kunai"; if (shotNum % 9 == 0) { RainbowCol = GetCol(255, 200, 97); } else { RainbowCol = GetCol(54, 104, 179); } shotOffset += 12 * Mathf.Sin(shotNum); doShoot = true; } break; case SkeleBulletType.INK: BulletTag = "Star"; System.Drawing.Color c = System.Drawing.Color.FromArgb((int)(RainbowCol.r * 255), (int)(RainbowCol.g * 255), (int)(RainbowCol.b * 255)); float hue = (c.GetHue() + shotNum / 7f) % 360 / 360f; RainbowCol = Color.HSVToRGB(hue, 0.6f, 1); gameObject.GetComponent <SpriteRenderer>().color = RainbowCol; shotOffset -= gameObject.transform.rotation.eulerAngles.z; Vector3 dir = (Vector3)dest - transform.position; float angle = Mathf.Atan2(dir.y, dir.x) * Mathf.Rad2Deg - 90; shotOffset += angle; scale = new Vector2(0.5f, 0.5f); doShoot = true; break; case SkeleBulletType.ERROR: BulletTag = "Kunai"; switch (Random.Range(0, 10)) { case 0: RainbowCol = Color.blue; break; case 1: RainbowCol = Color.red; break; case 2: RainbowCol = Color.yellow; break; default: RainbowCol = GetCol(74, 74, 74); break; } doShoot = true; break; case SkeleBulletType.CIDER: if (shotNum % 2 == 0) { BulletTag = "KunaiGreen"; } else { BulletTag = "KunaiPurple"; } if (shotNum % 2 == 0) { translate = Random.insideUnitCircle; } doShoot = true; break; case SkeleBulletType.CHRONOS: if (!onChronosSegment) { onChronosSegment = true; chronosCount = chronosNum; chronosNum--; if (chronosNum <= 0) { chronosNum = 1; } } if (chronosCount > 0) { chronosCount--; BulletTag = "Kunai"; RainbowCol = GetCol(0, 247, 255); doShoot = true; } else { onChronosSegment = false; } break; case SkeleBulletType.ZEPHYR: if (shotNum % 15 > 1) { BulletTag = "KunaiGreen"; shotOffset = shotNum; if (shotNum % 5 == 0) { shotOffset -= 180; BulletTag = "KunaiYellow"; } doShoot = true; } break; } if (doShoot) { StageController.AudioManager.PlaySFX("shootbullet", 0.1f); GameObject bullet = ObjectPooler.Spawn(BulletTag, transform.position, Quaternion.identity); if (scale != null) { bullet.transform.localScale = scale.Value; } if (BulletTag == "Kunai" || BulletTag == "Star") { SpriteRenderer rend = bullet.GetComponent <SpriteRenderer>(); rend.color = RainbowCol; rend.sortingOrder = (int)shotNum; } bullet.transform.Translate(translate); bullet.transform.Rotate(0, 0, transform.rotation.eulerAngles.z + shotOffset); if (BulletType == SkeleBulletType.ERROR) { Vector2 acc = Random.insideUnitCircle * 0.03f; bullet.GetOrAddComponent <SimpleMovement>().UpdateAcceleration(acc.x, acc.y); } if (BulletType == SkeleBulletType.ZEPHYR) { SkeletalSerenade.ZephyrBullets.Add(bullet); } bullets.Add(bullet); } shotNum++; } #endregion if (pullSpeed * frameNum >= 1) { card.ShootCirclesStart(EndCircleDelay, BulletTag, EndCircleRotation, transform.position, RainbowCol, BulletType); foreach (GameObject bullet in bullets) { bullet.GetOrAddComponent <SimpleMovement>().UpdateAcceleration(bullet.transform.up.x, bullet.transform.up.y); } ObjectPooler.Disable(gameObject); return; } }
private void HandleUnitSelection() { Vector2 temp = endBoxPos - orgBoxPos; Rectangle rect = new Rectangle((int)orgBoxPos.x, 480 - (int)(orgBoxPos.y), (int)(Mathf.Abs(temp.x)), (int)(Mathf.Abs(temp.y))); test = new Mat(frame, rect); Image <Bgr, Byte> imgBgr = test.ToImage <Bgr, byte>(); var moments = CvInvoke.Moments(imgBgr[0]); int cx = (int)(moments.M10 / moments.M00); int cy = (int)(moments.M01 / moments.M00); int b = 0, g = 0, r = 0; for (int i = 0; i < 5; i++) { Point pts1 = new Point(cx + i, cy + i); Point pts2 = new Point(cx - i, cy - i); Point pts3 = new Point(cx - i, cy + i); Point pts4 = new Point(cx + i, cy - i); r += (int)imgBgr[pts1].Red; r += (int)imgBgr[pts2].Red; r += (int)imgBgr[pts3].Red; r += (int)imgBgr[pts4].Red; g += (int)imgBgr[pts1].Green; g += (int)imgBgr[pts2].Green; g += (int)imgBgr[pts3].Green; g += (int)imgBgr[pts4].Green; b += (int)imgBgr[pts1].Blue; b += (int)imgBgr[pts2].Blue; b += (int)imgBgr[pts3].Blue; b += (int)imgBgr[pts4].Blue; } r = r / 20; g = g / 20; b = b / 20; System.Drawing.Color c = System.Drawing.Color.FromArgb(r, g, b); Hsv hsv = new Hsv(c.GetHue(), c.GetSaturation(), c.GetBrightness()); hTarget = hsv.Hue / 2; sTarget = hsv.Satuation; vTarget = hsv.Value; Mat tata = test.Clone(); CvInvoke.CvtColor(test, tata, ColorConversion.Bgr2Hsv); Image <Hsv, byte> ImgHSV = tata.ToImage <Hsv, byte>(); Image <Gray, byte> tarace = ImgHSV.InRange(new Hsv(hTarget - intensity, 0, 0), new Hsv(hTarget + intensity, 255, 255)); Mat hierarchy = new Mat(); VectorOfVectorOfPoint contours = new VectorOfVectorOfPoint(); CvInvoke.FindContours(tarace, contours, hierarchy, RetrType.List, ChainApproxMethod.ChainApproxNone); double biggestContourArea = 0; VectorOfPoint biggestContour = new VectorOfPoint(); int biggestContourIndex = 0; for (int i = 0; i < contours.Size; i++) { if (CvInvoke.ContourArea(contours[i]) > biggestContourArea) { biggestContour = contours[i]; biggestContourIndex = i; biggestContourArea = CvInvoke.ContourArea(contours[i]); } } Mat biggestContourMat = new Mat(test, CvInvoke.BoundingRectangle(contours[biggestContourIndex])); CvInvoke.Mean() // colorDetect = true; }
public override IEnumerator StartSpell() { int x = 0; const float target_comp = 23; const float b = 1.17f; const float start_comp = 12; const float comp_speed = 0.09f; const float path_threshold = 3f; float current_comp; float comp_accuracy; bool calcp = true; while (true) { ShootSFX(); if (calcp) { comp_accuracy = start_comp * Mathf.Pow(b, -x * comp_speed); if (comp_accuracy < 0.001f) { calcp = false; } current_comp = target_comp - comp_accuracy; } else { current_comp = target_comp; } float path = 7 * Mathf.Sin(current_comp * x * Mathf.Deg2Rad) + 9; int layerNum = 1; bool flip = false; for (int y = -3; y < 24; y++) { if (Mathf.Abs(y - path) <= path_threshold) { flip = true; continue; } GameObject bullet; if (Mathf.Abs(y + 1 - path) <= path_threshold || Mathf.Abs(y - 1 - path) <= path_threshold) { // If on edges, use the edge bullet bullet = ObjectPooler.Spawn("LevelBarEnd", new Vector3(15, y, 0), Quaternion.identity); } else { bullet = ObjectPooler.Spawn("LevelBarBody", new Vector3(15, y, 0), Quaternion.identity); } if (flip) { bullet.transform.Rotate(0, 0, 180); } SpriteRenderer rend = bullet.GetComponent <SpriteRenderer>(); rend.sortingOrder = layerNum++; System.Drawing.Color c = System.Drawing.Color.FromArgb((int)(rend.color.r * 255), (int)(rend.color.g * 255), (int)(rend.color.b * 255)); float hue = (c.GetHue() + x * 1.5f) % 360 / 360f; float sat = c.GetSaturation(); // float bri = c.GetBrightness(); rend.color = Color.HSVToRGB(hue, sat, 1); bullet.GetComponent <Rigidbody2D>().velocity = new Vector2(-4, 0); } x++; yield return(new WaitForSeconds(0.25f)); } }
/// <summary> /// 对原图进行基准白矫正1,效率比较低 /// </summary> /// <param name="bitimg"></param> /// <returns></returns> static public Bitmap NormalizedWhite(Bitmap bitimg) { Bitmap myimg = bitimg; int m = bitimg.Width; int n = bitimg.Height; double[,] H = new double[m, n]; double maxH = 0; for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { byte red = bitimg.GetPixel(i, j).R; byte green = bitimg.GetPixel(i, j).G; byte blue = bitimg.GetPixel(i, j).B; System.Drawing.Color color = System.Drawing.Color.FromArgb(red, green, blue); double hue = color.GetHue(); //double hue = 0.299*(double)red + 0.587*(double)green + 0.114*(double)blue; //double Cb = 0.564*((double)blue - hue); //double Cr = 0.713 * ((double)red - hue); if (maxH < hue)//找到最大的亮度数值 { maxH = hue; } H[i, j] = hue; float saturation = color.GetSaturation(); float lightness = color.GetBrightness(); } } double[] sortedH = new double[(int)maxH + 1];//用来存档排序后的亮度值 double sumI = 0; for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { sortedH[(int)H[i, j]]++; sumI += H[i, j];//求出图像的所有亮度和 } } double meanI = sumI / (m * n); //求出图像的平均亮度值 int count = (int)(sortedH.Count() * 0.05); //数据的总数n float sumR = 0; float sumG = 0; float sumB = 0; int countRGB = 0; for (int i = sortedH.Count(); i > sortedH.Count() - count; i--) { for (int ii = 0; ii < m; ii++)//遍历所有的图片像素 { for (int iii = 0; iii < n; iii++) { if (H[ii, iii] == i)//找到一样的像素 { sumR += bitimg.GetPixel(ii, iii).R; sumG += bitimg.GetPixel(ii, iii).G; sumB += bitimg.GetPixel(ii, iii).B; countRGB++; } } } } double meanR = sumR / countRGB; //基准白的R均值 double meanG = sumG / countRGB; //基准白的G均值 double meanB = sumB / countRGB; //基准白的B均值 double aR = meanR / meanG; //调整系数 double aG = meanG / meanI; double aB = meanB / meanI; for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { int colorR = (int)(bitimg.GetPixel(i, j).R *aR); int colorG = (int)(bitimg.GetPixel(i, j).G *aG); int colorB = (int)(bitimg.GetPixel(i, j).B *aB); int cR; int cG; int cB; if (double.IsNaN(aR * aG * aB)) { cR = double.IsNaN(aR) ? bitimg.GetPixel(i, j).R : colorR; cG = double.IsNaN(aG) ? bitimg.GetPixel(i, j).G : colorG; cB = double.IsNaN(aG) ? bitimg.GetPixel(i, j).B : colorB; } else { cR = colorR > 255 ? 255 : colorR; cG = colorG > 255 ? 255 : colorG; cB = colorB > 255 ? 255 : colorB; } Color cnew = Color.FromArgb(cR, cG, cB); myimg.SetPixel(i, j, cnew); } } //进行排序 return(myimg); }
private async void CreateCode_Button(object sender, RoutedEventArgs e) { if (openflag == false) { MessageBox.Show("開くファイルを選択してください", "コード生成エラー", MessageBoxButton.OK, MessageBoxImage.Information); return; } Bitmap bitmap = new Bitmap(Filepath); //描画用クラスのインスタンス化 int w = bitmap.Width; //画素の幅 int h = bitmap.Height; //画素の高さ progress.Minimum = 0; //最小値は0 progress.Maximum = h; //高さの分が最大値 if (w > 128 || h > 128) { MessageBox.Show("幅または高さが 128[px] を超えているものは生成できません。", "コード生成エラー", MessageBoxButton.OK, MessageBoxImage.Information); return; } status.Content = "ステータス:生成中..."; Textbox_code.Text = ""; Textbox_code.Text += "#define P_WIDTH " + w.ToString() + "\n"; Textbox_code.Text += "#define P_HEIGHT " + h.ToString() + "\n\n"; Textbox_code.Text += "const unsigned int pic_data[P_HEIGHT][P_WIDTH] = {\n"; for (int y = 0; y < h; y++) { Textbox_code.Text += "\t"; //タブスペース "\t" Textbox_code.Text += "{"; for (int x = 0; x < w; x++) { System.Drawing.Color pixel = bitmap.GetPixel(x, y); float H = pixel.GetHue(); float S = pixel.GetSaturation(); //0に行くほど白 float B = pixel.GetBrightness(); //0にいくほど黒 await Task.Run(() => { Color_value = ConvertColor(H, S, B); }); //Textbox_code.Text += "[" + H.ToString()+ " " + S.ToString() + " " + B.ToString() + "]"; //数値確認 Textbox_code.Text += Color_value.ToString(); if (x == w - 1) { Textbox_code.Text += ""; } else { Textbox_code.Text += ", "; } } //Invoke は他のタスクで使用されているコントローラに操作する権利を与える //非同期処理で進捗率も示す。 await Task.Run(() => { Dispatcher.Invoke((Action)(() => { progress.Value = y + 1; })); }); Textbox_code.Text += "},\n"; } Textbox_code.Text += "};\n"; saveflag = true; status.Content = "ステータス:完了"; }