public static int[] CreateDottedImage(int width, int height)
		{
			Random rnd = new Random();
			const int pointsNum = 100000;
			const double radius = 1.5;

			var randomPoints = Enumerable.Range(0, pointsNum).Select(_ => new Point(rnd.NextDouble() * width, rnd.NextDouble() * height));
			randomPoints = Filter(randomPoints, radius);

			DrawingGroup drawing = new DrawingGroup();
			var dc = drawing.Append();
			foreach (var point in randomPoints)
			{
				HsbColor color = new HsbColor(0, 0, Math.Round(5 * rnd.NextDouble()) / 4);
				SolidColorBrush brush = new SolidColorBrush(color.ToArgbColor());

				//drawing.Children.Add(new GeometryDrawing(brush, null, new EllipseGeometry(point, radius, radius)));
				dc.DrawEllipse(brush, null, point, radius, radius);
			}
			dc.Close();

			DrawingImage drawingImage = new DrawingImage();
			drawingImage.Drawing = drawing;
			drawingImage.Freeze();

			if ((imageCreatingThread.ThreadState | ThreadState.Running) != imageCreatingThread.ThreadState)
				imageCreatingThread.Start();
			imageQueue.Add(new RequestInfo { Width = width, Heigth = height, DrawingImage = drawingImage });
			var pixels = resultQueue.Take();

			return pixels;
		}
Beispiel #2
0
        void InitSymbol(Symbol s, string property)
        {
            s.Color = ChartViewModel._Colors[IndexMemory % ChartViewModel._Colors.Length];
            IndexMemory++;
            HsbColor hsb = ColorEx.RgbToHsb(s.Color);

            s.MovingAverage = new C1.Xaml.Chart.Finance.MovingAverage()
            {
                Binding = property,
                Type    = MovingAverageType.Simple,
                Period  = 10,
            };

            s.MovingAverage.Visibility             = _viewModel.IsShowMovingAverage ? SeriesVisibility.Visible : SeriesVisibility.Hidden;
            s.MovingAverage.Style                  = new ChartStyle();
            s.MovingAverage.Style.Fill             = s.MovingAverage.Style.Stroke
                                                   = new SolidColorBrush(ColorEx.HsbToRgb(new HsbColor()
            {
                A = hsb.A, H = hsb.H, S = Math.Max(hsb.B / 2, 0), B = Math.Min(hsb.B * 2, 1)
            }));
            s.MovingAverage.ItemsSource = s.DataSource;

            s.Series = new Series()
            {
                Binding = property, SeriesName = s.Code.ToUpper()
            };
            s.Series.ChartType             = ChartType.Line;
            s.Series.Style                 = new ChartStyle();
            s.Series.Style.StrokeThickness = 2;
            s.Series.Style.Fill            = new SolidColorBrush(Windows.UI.Color.FromArgb(64, s.Color.R, s.Color.G, s.Color.B));
            s.Series.Style.Stroke          = new SolidColorBrush(s.Color);
            s.Series.ItemsSource           = s.DataSource;
        }
		private BitmapSource CreateWhiteNoizeBmp(int width, int height)
		{
			var dataSource = DataSource;
			Random rnd = new Random();
			int[] pixels = new int[width * height];
			for (int i = 0; i < width * height; i++)
			{
				HsbColor color = new HsbColor(0, 0, Math.Round(5 * rnd.NextDouble()) / 4);
				int argb = color.ToArgb();
				pixels[i] = argb;
			}
			//var whiteNoizeBmp = WriteableBitmap.Create(width, height, 96, 96, PixelFormats.Pbgra32, null, pixels, width * 4);

			var contentBounds = dataSource.Grid.GetGridBounds();
			Viewport2D.SetContentBounds(this, contentBounds);

			int[] effectivePixels = CreateConvolutionArray(width, height, pixels);

			var filter = new NormalizeFilter();
			filter.Filter(effectivePixels, width, height);

			var result = WriteableBitmap.Create(width, height, 96, 96, PixelFormats.Pbgra32, null, effectivePixels, width * 4);
			//ScreenshotHelper.SaveBitmapToFile(result, "1.png");

			return result;
		}
Beispiel #4
0
        /// <summary>
        /// Helper method for initalizing the voice service, bridge, and lights. Returns if successful.
        /// </summary>
        private async Task <bool> InitializeAsync(AppServiceTriggerDetails triggerDetails)
        {
            _voiceServiceConnection =
                VoiceCommandServiceConnection.FromAppServiceTriggerDetails(triggerDetails);
            _voiceServiceConnection.VoiceCommandCompleted += (s, e) => _deferral.Complete();

            _voiceCommand = await _voiceServiceConnection.GetVoiceCommandAsync();

            _colors = HsbColor.CreateAll().ToDictionary(x => x.Name);

            var localStorage = ApplicationData.Current.LocalSettings.Values;

            _bridge = new Bridge(
                localStorage["bridgeIp"].ToString(), localStorage["userId"].ToString());
            try
            {
                _lights = await _bridge.GetLightsAsync();
            }
            catch (Exception)
            {
                var response = CreateCortanaResponse("Sorry, I couldn't connect to your bridge.");
                await _voiceServiceConnection.ReportFailureAsync(response);

                return(false);
            }
            if (!_lights.Any())
            {
                var response = CreateCortanaResponse("Sorry, I couldn't find any lights.");
                await _voiceServiceConnection.ReportFailureAsync(response);

                return(false);
            }
            return(true);
        }
        private BitmapSource CreateWhiteNoizeBmp(int width, int height)
        {
            var    dataSource = DataSource;
            Random rnd        = new Random();

            int[] pixels = new int[width * height];
            for (int i = 0; i < width * height; i++)
            {
                HsbColor color = new HsbColor(0, 0, Math.Round(5 * rnd.NextDouble()) / 4);
                int      argb  = color.ToArgb();
                pixels[i] = argb;
            }
            //var whiteNoizeBmp = WriteableBitmap.Create(width, height, 96, 96, PixelFormats.Pbgra32, null, pixels, width * 4);

            var contentBounds = dataSource.Grid.GetGridBounds();

            Viewport2D.SetContentBounds(this, contentBounds);

            int[] effectivePixels = CreateConvolutionArray(width, height, pixels);

            var filter = new NormalizeFilter();

            filter.Filter(effectivePixels, width, height);

            var result = WriteableBitmap.Create(width, height, 96, 96, PixelFormats.Pbgra32, null, effectivePixels, width * 4);

            //ScreenshotHelper.SaveBitmapToFile(result, "1.png");

            return(result);
        }
        private void Page_Loaded(object sender, RoutedEventArgs e)
        {
            AddRandomPoint();
            AddRandomPoint();
            AddRandomPoint();

            // these are functions that sets different properties of drawn ellipses;
            // these functions can be replaced by real, non-demo ones.
            chart.AddPropertyBindingForNamedPart <Point>("ellipse", Ellipse.FillProperty, p =>
            {
                double hue = Math.Sin(1000 * (p.X + p.Y)) * 180 + 180;
                var color  = new HsbColor(hue, 0.2, 1);
                return(new SolidColorBrush(color.ToArgbColor()).MakeTransparent(0.7));
            });
            chart.AddPropertyBindingForNamedPart <Point>("ellipse", Ellipse.StrokeProperty, p =>
            {
                double hue = Math.Sin(1000 * (p.X + p.Y)) * 180 + 180;
                var color  = new HsbColor(hue, 1, 1);
                return(new SolidColorBrush(color.ToArgbColor()));
            });
            chart.AddPropertyBindingForNamedPart <Point>("ellipse", Ellipse.RenderTransformProperty, p => new RotateTransform(120 * Math.Atan2(p.Y, p.X)));
            chart.AddPropertyBinding <Point>(ViewportPanel.ViewportWidthProperty, p => 0.2 * Math.Abs(Math.Sin(p.X)));
            chart.AddPropertyBinding <Point>(ViewportPanel.ViewportHeightProperty, p => 0.2 * Math.Abs(Math.Cos(p.X)));

            DataContext = points;
        }
        public override void ApplyFilter(int[] pixels, int width, int height, Vector[,] field)
        {
            double minBrightness = Double.PositiveInfinity;
            double maxBrightness = Double.NegativeInfinity;

            for (int i = 0; i < pixels.Length; i++)
            {
                int x = i % width;
                int y = i / width;

                int argb       = pixels[i];
                var color      = HsbColor.FromArgb(argb);
                var brightness = color.Brightness;

                if (brightness < minBrightness)
                {
                    minBrightness = brightness;
                }
                if (brightness > maxBrightness)
                {
                    maxBrightness = brightness;
                }
            }

            for (int i = 0; i < pixels.Length; i++)
            {
                int argb       = pixels[i];
                var color      = HsbColor.FromArgb(argb);
                var brightness = color.Brightness;

                double ratio = (brightness - minBrightness) / (maxBrightness - minBrightness);
                color.Brightness = ratio;
                pixels[i]        = color.ToArgb();
            }
        }
        public override int[] ApplyFilter(int[] pixels, int width, int height, Vector[,] field)
        {
            double maxLength = Double.NegativeInfinity;
            double minLength = Double.PositiveInfinity;

            // determine min and max length
            // this works faster than parallel enumerable version.
            for (int ix = 0; ix < width; ix++)
            {
                for (int iy = 0; iy < height; iy++)
                {
                    var length = field[ix, iy].Length;
                    if (length > maxLength)
                    {
                        maxLength = length;
                    }
                    if (length < minLength)
                    {
                        minLength = length;
                    }
                }
            }

            int[] resultPixels = new int[width * height];
            pixels.CopyTo(resultPixels, 0);

            // attempt to avoid exception on line
            // 'HsbColor color = HsbColor.FromArgb(pixels[i]);'
            if (pixels.Length == 0)
            {
                return(pixels);
            }

            Parallel.For(0, width * height, i =>
            {
                HsbColor color = HsbColor.FromArgb(pixels[i]);

                int ix     = i % width;
                int iy     = i / width;
                var length = field[ix, height - 1 - iy].Length;

                var ratio = (length - minLength) / (maxLength - minLength);
                if (ratio.IsNaN())
                {
                    ratio = 0;
                }

                var paletteColor = Palette.GetColor(ratio).ToHsbColor();

                color.Hue        = paletteColor.Hue;
                color.Saturation = paletteColor.Saturation;

                resultPixels[i] = color.ToArgb();
            });

            return(resultPixels);
        }
Beispiel #9
0
        public static string HsbToString(this HsbColor hsbColor)
        {
            var sb = new StringBuilder("hsva(");

            sb.Append(hsbColor.H.ToString(CultureInfo.InvariantCulture) + ", ");
            sb.Append(hsbColor.S.ToString(CultureInfo.InvariantCulture) + ", ");
            sb.Append(hsbColor.B.ToString(CultureInfo.InvariantCulture) + ", ");
            sb.Append(hsbColor.A.ToString(CultureInfo.InvariantCulture) + ")");
            return(sb.ToString());
        }
Beispiel #10
0
 public static HsbColor InvertValue(this HsbColor col)
 {
     return(new HsbColor
     {
         H = col.H,
         S = col.S,
         B = 1 - col.B,
         A = col.A
     });
 }
Beispiel #11
0
        private static void GenerateWhiteNoizeImage(int width, int height, int[] pixels)
        {
            Random rnd = new Random();

            for (int i = 0; i < width * height; i++)
            {
                HsbColor color = new HsbColor(0, 0, Math.Round(5 * rnd.NextDouble()) / 4);
                int      argb  = color.ToArgb();
                pixels[i] = argb;
            }
        }
Beispiel #12
0
        private List <Vertex.PositionColored> BuildVertices(PointSet pointSet, double altitude)
        {
            List <Vertex.PositionColored> vertices = new List <Vertex.PositionColored>();

            double minT = 0, maxT = 0, k;

            if (!Double.IsNaN(pointSet.MaxValue))
            {
                minT = pointSet.MinValue;
                maxT = pointSet.MaxValue;
                k    = 1.0 / (maxT - minT);
            }
            else
            {
                k = Double.NaN;
            }

            for (int j = 0; j < pointSet.Data.Count; j++)
            {
                float     x        = (float)pointSet.Data[j].Longitude;
                float     y        = (float)pointSet.Data[j].Latitude;
                LatLonAlt position = LatLonAlt.CreateUsingDegrees(y + step, x + step, altitude);
                Vector3F  vec      = new Vector3F(position.GetVector());

                double hue;
                Color  color = Color.Red;
                System.Windows.Media.Color tempColor;

                if (!Double.IsNaN(k))
                {
                    hue       = 270 * ((maxT - (double)pointSet.Data[j].Value) * k);
                    tempColor = new HsbColor(hue, 1, 1, 0.8).ToArgb();
                    color     = Color.FromArgb(tempColor.A, tempColor.R, tempColor.G, tempColor.B);
                }

                vertices.Add(new Vertex.PositionColored(vec, color.ToArgb()));

                position = LatLonAlt.CreateUsingDegrees(y - step, x - step, altitude);
                vec      = new Vector3F(position.GetVector());
                vertices.Add(new Vertex.PositionColored(vec, color.ToArgb()));

                position = LatLonAlt.CreateUsingDegrees(y + step, x - step, altitude);
                vec      = new Vector3F(position.GetVector());
                vertices.Add(new Vertex.PositionColored(vec, color.ToArgb()));

                position = LatLonAlt.CreateUsingDegrees(y - step, x + step, altitude);
                vec      = new Vector3F(position.GetVector());
                vertices.Add(new Vertex.PositionColored(vec, color.ToArgb()));
            }

            return(vertices);
        }
Beispiel #13
0
		public static int[] CreateWhiteNoizeImage(int width, int height)
		{
			int[] pixels = new int[width * height];

			Random rnd = new Random();
			for (int i = 0; i < width * height; i++)
			{
				HsbColor color = new HsbColor(0, 0, Math.Round(5 * rnd.NextDouble()) / 4);
				int argb = color.ToArgb();
				pixels[i] = argb;
			}

			return pixels;
		}
Beispiel #14
0
        public static int[] CreateWhiteNoizeImage(int width, int height)
        {
            int[] pixels = new int[width * height];

            Random rnd = new Random();

            for (int i = 0; i < width * height; i++)
            {
                HsbColor color = new HsbColor(0, 0, Math.Round(5 * rnd.NextDouble()) / 4);
                int      argb  = color.ToArgb();
                pixels[i] = argb;
            }

            return(pixels);
        }
        /// <summary>
        /// Prepares Cortana for background use.
        /// </summary>
        private async Task InitializeCortanaAsync()
        {
            // You can't write to application files by default, so we need to create a
            // secondary VCD file to dynamically write Cortana commands to.
            StorageFile dynamicFile = await ApplicationData.Current.RoamingFolder.CreateFileAsync(
                "VoiceCommands.xml", CreationCollisionOption.ReplaceExisting);

            // Load the base file and parse the PhraseList we want from it.
            StorageFile baseFile = await StorageFile.GetFileFromApplicationUriAsync(
                new Uri("ms-appx:///VoiceCommands.xml"));

            XDocument xml   = XDocument.Load(baseFile.Path);
            XElement  state = xml.Descendants().First(x => x.Name.LocalName == "PhraseList" &&
                                                      null != x.Attribute("Label") && x.Attribute("Label").Value == "state");

            // A ColorMapping is a RGB and HSV compliant representation a system color.
            // ColorMapping.CreateAll() returns a ColorMapping for all system colors available to UWP apps.
            // For each ColorMapping, add it to the list of phrases Cortana knows.
            foreach (HsbColor color in HsbColor.CreateAll())
            {
                state.Add(new XElement("Item", color.Name));
            }

            // Add the light names.
            XElement names = xml.Descendants().First(x => x.Name.LocalName == "PhraseList" &&
                                                     null != x.Attribute("Label") && x.Attribute("Label").Value == "name");

            foreach (Light light in _lights)
            {
                names.Add(new XElement("Item", light.Name));
            }

            // Save the file, and then load so Cortana recognizes it.
            using (Stream stream = await dynamicFile.OpenStreamForWriteAsync())
            {
                xml.Save(stream);
            }
            try
            {
                await VoiceCommandDefinitionManager.InstallCommandDefinitionsFromStorageFileAsync(dynamicFile);
            }
            catch (FileNotFoundException)
            {
                // Do nothing. This is a workaround for a spurious FileNotFoundException that
                // is thrown even though dynamicFile exists on disk.
            }
        }
Beispiel #16
0
        private void InitPalette()
        {
            var brushes = from prop in typeof(Brushes).GetProperties()
                          let brush = (SolidColorBrush)prop.GetValue(null, null)
                                      let hsbColor = HsbColor.FromArgbColor(brush.Color)
                                                     orderby hsbColor.Hue
                                                     select new SolidColorBrush(hsbColor.ToArgbColor());

            AlternationConverter converter = new AlternationConverter();

            foreach (var brush in brushes)
            {
                converter.Values.Add(brush);
            }

            Resources.Add("fillsConverter", converter);
        }
Beispiel #17
0
        private static void ChangeFill(Ellipse ellipse, double sign)
        {
            Color    fill = ((SolidColorBrush)ellipse.Fill).Color;
            HsbColor hsb  = fill.ToHsbColor();

            hsb.Hue = (hsb.Hue + sign * 70) % 360;
            Color newColor = hsb.ToArgbColor();

            if (newColor.A == 0 || (newColor.R == 0 && newColor.G == 0 && newColor.B == 0))
            {
                Debugger.Break();
            }

            var brush = new SolidColorBrush(newColor);

            ellipse.Fill = brush;
        }
        public Color GetColor(double t)
        {
            Verify.AssertIsFinite(t);
            Verify.IsTrue(0 <= t && t <= 1);

            if (t <= 0)
            {
                return(colors[0]);
            }
            else if (t >= 1)
            {
                return(colors[colors.Count - 1]);
            }
            else
            {
                int i = 0;
                while (points[i] < t)
                {
                    i++;
                }

                double ratio = (points[i] - t) / (points[i] - points[i - 1]);

                Verify.IsTrue(0 <= ratio && ratio <= 1);

                Color c0  = colors[i - 1];
                Color c1  = colors[i];
                Color res = Color.FromRgb(
                    (byte)(c0.R * ratio + c1.R * (1 - ratio)),
                    (byte)(c0.G * ratio + c1.G * (1 - ratio)),
                    (byte)(c0.B * ratio + c1.B * (1 - ratio)));

                // Increasing saturation and brightness
                if (increaseBrightness)
                {
                    HsbColor hsb = res.ToHsbColor();
                    //hsb.Saturation = 0.5 * (1 + hsb.Saturation);
                    hsb.Brightness = 0.5 * (1 + hsb.Brightness);
                    return(hsb.ToArgbColor());
                }
                else
                {
                    return(res);
                }
            }
        }
        private EnumerableDataSource <DataPoint> CreateDataSource(IEnumerable <DataPoint> data)
        {
            EnumerableDataSource <DataPoint> ds = new EnumerableDataSource <DataPoint>(data);

            MercatorTransform transform = new MercatorTransform();

            ds.SetXMapping(p => p.X);
            ds.SetYMapping(p => transform.DataToViewport(new Point(0, p.Y)).Y);
            ds.AddMapping(CirclePointMarker.FillProperty, dp =>
            {
                double alpha = (dp.Data - currentRange.Min) / (currentRange.Max - currentRange.Min);

                Debug.Assert(0 <= alpha && alpha <= 1);

                const double hueWidth = 100;
                double hue            = hueWidth * (alpha - 0.5) + hueSlider.Value;

                if (hue > 360)
                {
                    hue -= 360;
                }
                else if (hue < 0)
                {
                    hue += 360;
                }

                Debug.Assert(0 <= hue && hue <= 360);

                Color mainColor = new HsbColor(hue, 1, 0 + 1 * alpha, 0.3 + 0.7 * alpha).ToArgbColor();

                const int colorCount          = 5;
                GradientStopCollection colors = new GradientStopCollection(colorCount);

                double step = 1.0 / (colorCount - 1);
                for (int i = 0; i < colorCount; i++)
                {
                    Color color = mainColor;
                    double x    = attSlider.Value * step * i;
                    color.A     = (byte)(255 * Math.Exp(-x * x));
                    colors.Add(new GradientStop(color, step * i));
                }

                return(new RadialGradientBrush(colors));
            });
            return(ds);
        }
        private void CreateNoizeTexture(GraphicsDevice device)
        {
            const int size = 512;

            noizeTexture = new Texture2D(device, size, size);

            int[]  noizeData = new int[size * size];
            Random rnd       = new Random();

            for (int i = 0; i < size * size; i++)
            {
                HsbColor color = new HsbColor(0, 0, Math.Round(5 * rnd.NextDouble()) / 4);
                int      argb  = color.ToArgb();
                noizeData[i] = argb;
            }

            noizeTexture.SetData(noizeData);
        }
        public static void Test()
        {
            Color c1 = Color.OrangeRed;
            Color c2 = Color.GreenYellow;
            Color c3 = ColorTranslator.FromHtml(@"#0066CC");
            Color c4 = ColorTranslator.FromHtml(@"#FF0000");

            RgbColor color01 = new RgbColor(255, 0, 0);
            RgbColor color02 = new RgbColor(0, 255, 0);
            RgbColor color03 = new RgbColor(0, 0, 255);

            RgbColor color04 = new RgbColor(255, 255, 0);
            RgbColor color05 = new RgbColor(255, 0, 255);
            RgbColor color06 = new RgbColor(0, 255, 255);

            RgbColor color07 = new RgbColor(0, 0, 0);
            RgbColor color08 = new RgbColor(255, 255, 255);

            // --

            //HsbColor hsb01 = HsbColor.FromColor( color01 );
            //HsbColor hsb02 = new HsbColor(
            //(int)color01.GetHue(),
            //(int)(color01.GetSaturation()*100),
            //(int)(color01.GetBrightness()*100) );

            HslColor hsl02 = HslColor.FromRgbColor(color02);
            HsbColor hsb01 = HsbColor.FromRgbColor(color01);

            //HslColor hsl02 = new HslColor(
            //    (int)color01.GetHue(),
            //    (int)(color01.GetSaturation() * 100),
            //    (int)(color01.GetBrightness() * 100) );

            RgbColor r = hsl02.ToRgbColor();

            RgbColor o1 = new RgbColor(115, 72, 50);
            HslColor o2 = o1.ToHslColor();
            RgbColor o3 = o2.ToRgbColor();

            // --

            int i = 0;
        }
        public override void ApplyFilter(int[] pixels, int width, int height, Vector[,] field)
        {
            double maxLength = Double.NegativeInfinity;
            double minLength = Double.PositiveInfinity;

            for (int ix = 0; ix < width; ix++)
            {
                for (int iy = 0; iy < height; iy++)
                {
                    var length = field[ix, iy].Length;
                    if (length > maxLength)
                    {
                        maxLength = length;
                    }
                    if (length < minLength)
                    {
                        minLength = length;
                    }
                }
            }

            for (int i = 0; i < width * height; i++)
            {
                HsbColor color = HsbColor.FromArgb(pixels[i]);

                int ix     = i % width;
                int iy     = i / width;
                var length = field[ix, iy].Length;

                var ratio = (length - minLength) / (maxLength - minLength);
                if (ratio.IsNaN())
                {
                    ratio = 0;
                }

                var paletteColor = Palette.GetColor(ratio).ToHsbColor();

                color.Hue        = paletteColor.Hue;
                color.Saturation = paletteColor.Saturation;

                pixels[i] = color.ToArgb();
            }
        }
Beispiel #23
0
 public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
 {
     if (value is Color c)
     {
         var color = new HsbColor(c);
         var brush = new LinearGradientBrush()
         {
             StartPoint = new Point(0, 0),
             EndPoint   = new Point(1, 0),
         };
         for (decimal hue = 0M; hue <= 360M; hue += 60M)
         {
             color.Hue = hue;
             var stop = new GradientStop(color, (double)hue / 360.0);
             brush.GradientStops.Add(stop);
         }
         return(brush);
     }
     throw new ArgumentException();
 }
Beispiel #24
0
        public static int[] CreateDottedImage(int width, int height)
        {
            Random       rnd       = new Random();
            const int    pointsNum = 100000;
            const double radius    = 1.5;

            var randomPoints = Enumerable.Range(0, pointsNum).Select(_ => new Point(rnd.NextDouble() * width, rnd.NextDouble() * height));

            randomPoints = Filter(randomPoints, radius);

            DrawingGroup drawing = new DrawingGroup();
            var          dc      = drawing.Append();

            foreach (var point in randomPoints)
            {
                HsbColor        color = new HsbColor(0, 0, Math.Round(5 * rnd.NextDouble()) / 4);
                SolidColorBrush brush = new SolidColorBrush(color.ToArgbColor());

                //drawing.Children.Add(new GeometryDrawing(brush, null, new EllipseGeometry(point, radius, radius)));
                dc.DrawEllipse(brush, null, point, radius, radius);
            }
            dc.Close();

            DrawingImage drawingImage = new DrawingImage();

            drawingImage.Drawing = drawing;
            drawingImage.Freeze();

            if ((imageCreatingThread.ThreadState | ThreadState.Running) != imageCreatingThread.ThreadState)
            {
                imageCreatingThread.Start();
            }
            imageQueue.Add(new RequestInfo {
                Width = width, Heigth = height, DrawingImage = drawingImage
            });
            var pixels = resultQueue.Take();

            return(pixels);
        }
Beispiel #25
0
        public override int[] ApplyFilter(int[] pixels, int width, int height, Vector[,] field)
        {
            double minBrightness = Double.PositiveInfinity;
            double maxBrightness = Double.NegativeInfinity;

            for (int i = 0; i < pixels.Length; i++)
            {
                int argb       = pixels[i];
                var color      = HsbColor.FromArgb(argb);
                var brightness = color.Brightness;

                if (brightness < minBrightness)
                {
                    minBrightness = brightness;
                }
                if (brightness > maxBrightness)
                {
                    maxBrightness = brightness;
                }
            }

            if (minBrightness == 0 || maxBrightness == 1)
            {
                return(pixels);
            }

            Parallel.For(0, pixels.Length, i =>
            {
                int argb       = pixels[i];
                var color      = HsbColor.FromArgb(argb);
                var brightness = color.Brightness;

                double ratio     = (brightness - minBrightness) / (maxBrightness - minBrightness);
                color.Brightness = ratio;
                pixels[i]        = color.ToArgb();
            });

            return(pixels);
        }
Beispiel #26
0
        protected override void Apply(ImageBase target, ImageBase source, Rectangle rectangle, int startY, int endY)
        {
            if (UseHsbSpace)
            {
                HsbColor tint = HsbColor.FromRgb(TintColor);

                for (int y = startY; y < endY; y++)
                {
                    for (int x = rectangle.X; x < rectangle.Right; x++)
                    {
                        Color color = source[x, y];

                        HsbColor hsb = HsbColor.FromRgb(color);

                        hsb.H  = tint.H;
                        hsb.A *= tint.A;

                        target[x, y] = hsb.ToRgb();
                    }
                }
            }
            else
            {
                for (int y = startY; y < endY; y++)
                {
                    for (int x = rectangle.X; x < rectangle.Right; x++)
                    {
                        Color color = source[x, y];

                        target[x, y] = new Color(
                            r: (byte)(color.R * TintColor.R / 255),
                            g: (byte)(color.G * TintColor.G / 255),
                            b: (byte)(color.B * TintColor.B / 255),
                            a: color.A);
                    }
                }
            }
        }
        /// <summary>
        /// 单色Hsb 8色
        /// </summary>
        /// <param name="image">需要处理的图像</param>
        public static unsafe void MonochromeHSB8(Bitmap image)
        {
            int        w = image.Width; int h = image.Height;
            BitmapData data   = image.LockBits(new Rectangle(0, 0, w, h), ImageLockMode.ReadWrite, PixelFormat.Format24bppRgb);
            byte *     p      = (byte *)data.Scan0;
            int        offset = data.Stride - w * 3;

            for (int y = 0; y < h; y++)
            {
                for (int x = 0; x < w; x++)
                {
                    HsbColor hsb = HsbColor.FromRGB(p[0], p[1], p[2]);


                    if (hsb.Brightness < 0.35F)
                    {
                        //黑色
                        p[0] = p[1] = p[2] = 0;
                        //灰度 0
                    }
                    else if (hsb.Saturation < 0.15F && hsb.Brightness > 0.75F)
                    {
                        //白色
                        p[0] = p[1] = p[2] = 255;
                        //灰度 255
                    }
                    else if (hsb.Saturation < 0.15F && 0.35F < hsb.Brightness && hsb.Brightness < 0.75F)
                    {
                        //灰色
                        p[0] = p[1] = p[2] = 128;
                        //灰度 128
                    }
                    else if (hsb.Brightness >= 0.35F && hsb.Saturation >= 0.15F)
                    {
                        //彩色

                        if ((hsb.Hue >= 0 && hsb.Hue < 15) || (hsb.Hue >= 340 && hsb.Hue < 360))
                        {
                            //红色相近
                            p[0] = 255; p[1] = 0; p[2] = 0;
                            //灰度 40
                        }
                        else if (hsb.Hue >= 15 && hsb.Hue < 75)
                        {
                            //黄色相近
                            p[0] = 255; p[1] = 255; p[2] = 0;
                            //灰度 80
                        }
                        else if (hsb.Hue >= 75 && hsb.Hue < 150)
                        {
                            //绿色相近
                            p[0] = 0; p[1] = 255; p[2] = 0;
                            //灰度 120
                        }
                        else if (hsb.Hue >= 150 && hsb.Hue < 185)
                        {
                            //青色相近
                            p[0] = 0; p[1] = 255; p[2] = 255;
                            //灰度 160
                        }
                        else if (hsb.Hue >= 185 && hsb.Hue < 270)
                        {
                            //蓝色相近
                            p[0] = 0; p[1] = 0; p[2] = 255;
                            //灰度 200
                        }
                        else if (hsb.Hue >= 270 && hsb.Hue < 340)
                        {
                            //洋红
                            p[0] = 255; p[1] = 0; p[2] = 255;
                            //灰度 220
                        }
                        else
                        {
                            // * 紫色
                            p[0] = 128; p[1] = 0; p[2] = 128;
                            //灰度 180
                        }
                    }
                    p += 3;
                }
                p += offset;
            }
            image.UnlockBits(data);
        }
Beispiel #28
0
        /// <summary>
        /// Converts an RGB color to an HSB color.
        /// </summary>
        /// <param name="rgbColor">The RGB color to convert.</param>
        /// <returns>The HSB color equivalent of the RGBA color passed in.</returns>
        /// <remarks>Source: http://msdn.microsoft.com/en-us/library/ms771620.aspx</remarks>
        public static HsbColor RgbToHsb(Color rgbColor)
        {
            /* Hue values range between 0 and 360. All
             * other values range between 0 and 1. */

            // Create HSB color object
            var hsbColor = new HsbColor();

            // Get RGB color component values
            var r = (int)rgbColor.R;
            var g = (int)rgbColor.G;
            var b = (int)rgbColor.B;
            var a = (int)rgbColor.A;

            // Get min, max, and delta values
            double min = Math.Min(Math.Min(r, g), b);
            double max = Math.Max(Math.Max(r, g), b);
            double delta = max - min;

            /* Black (max = 0) is a special case. We
             * simply set HSB values to zero and exit. */

            // Black: Set HSB and return
            if (max == 0.0)
            {
                hsbColor.H = 0.0;
                hsbColor.S = 0.0;
                hsbColor.B = 0.0;
                hsbColor.A = a;
                return hsbColor;
            }

            /* Now we process the normal case. */

            // Set HSB Alpha value
            var alpha = (double)a;
            hsbColor.A = alpha / 255;

            // Set HSB Hue value
            if (r == max) hsbColor.H = (g - b) / delta;
            else if (g == max) hsbColor.H = 2 + (b - r) / delta;
            else if (b == max) hsbColor.H = 4 + (r - g) / delta;
            hsbColor.H *= 60;
            if (hsbColor.H < 0.0) hsbColor.H += 360;

            // Set other HSB values
            hsbColor.S = delta / max;
            hsbColor.B = max / 255;

            // Set return value
            return hsbColor;
        }
        public RasterPatch2 GetTilePatch(PointSet pointSet, Box2 regionBox, double iconSize)
        {
            GeoRect tileBox = new GeoRect(
                regionBox.MinCoordinate.X,
                regionBox.MinCoordinate.Y,
                regionBox.MaxCoordinate.X - regionBox.MinCoordinate.X,
                regionBox.MaxCoordinate.Y - regionBox.MinCoordinate.Y);

            int      width        = 256;
            int      height       = 256;
            Bitmap   resultBitmap = new Bitmap(width, height);
            Graphics graphics     = Graphics.FromImage(resultBitmap);

            double minT = 0, maxT = 0, k;

            if (!Double.IsNaN(pointSet.MaxValue))
            {
                minT = pointSet.MinValue;
                maxT = pointSet.MaxValue;
                k    = 1.0 / (maxT - minT);
            }
            else
            {
                k = Double.NaN;
            }

            ColorMatrix     colorMatrix = new ColorMatrix();
            ImageAttributes imageAttributes = new ImageAttributes();


            for (int i = 0; i < pointSet.Data.Count; i++)
            {
                GeoRect workingRect = new GeoRect(
                    pointSet.Data[i].Longitude - iconSize / 2.0,
                    pointSet.Data[i].Latitude - iconSize / 2.0,
                    iconSize,
                    iconSize);

                if (GeoRect.IntersectionExist(workingRect, tileBox))
                {
                    int x0 = (int)(Math.Min(width, Math.Max(0, pointSet.Data[i].Longitude - iconSize / 2.0 - tileBox.Left) / tileBox.Width * width));
                    int y0 = (int)(Math.Min(height, Math.Max(0, tileBox.Top - pointSet.Data[i].Latitude - iconSize / 2.0) / tileBox.Height * height));

                    int x1 = (int)(Math.Min(width, Math.Max(0, pointSet.Data[i].Longitude + iconSize / 2.0 - tileBox.Left) / tileBox.Width * width));
                    int y1 = (int)(Math.Min(height, Math.Max(0, tileBox.Top - pointSet.Data[i].Latitude + iconSize / 2.0) / tileBox.Height * height));

                    double widthX  = Math.Min(tileBox.Width, iconSize);
                    double heightY = Math.Min(tileBox.Height, iconSize);



                    lock (icon)
                    {
                        System.Windows.Media.Color tempColor = System.Windows.Media.Brushes.Red.Color;
                        if (!Double.IsNaN(k))
                        {
                            double hue = 270 * ((maxT - (double)pointSet.Data[i].Value) * k);
                            tempColor = new HsbColor(hue, 1, 1, 0.8).ToArgb();
                        }

                        colorMatrix.Matrix00 = (float)tempColor.R / 255f;
                        colorMatrix.Matrix11 = (float)tempColor.G / 255f;
                        colorMatrix.Matrix22 = (float)tempColor.B / 255f;


                        imageAttributes.SetColorMatrix(colorMatrix,
                                                       ColorMatrixFlag.Default,
                                                       ColorAdjustType.Bitmap);

                        int x2 = 0;
                        if (pointSet.Data[i].Longitude - iconSize / 2.0 < tileBox.Left)
                        {
                            x2 = icon.Width - (int)((double)(x1 - x0) * icon.Width / (widthX / tileBox.Width * width));
                        }

                        int y2 = 0;
                        if (tileBox.Top - pointSet.Data[i].Latitude - iconSize / 2.0 < 0)
                        {
                            y2 = icon.Height - (int)((double)(y1 - y0) * icon.Height / (heightY / tileBox.Height * height));
                        }

                        graphics.DrawImage(
                            icon,
                            new Rectangle(x0, y0, x1 - x0, y1 - y0),
                            x2,
                            y2,
                            (int)((double)(x1 - x0) * icon.Width / (widthX / tileBox.Width * width)),
                            (int)((double)(y1 - y0) * icon.Height / (heightY / tileBox.Height * height)),
                            GraphicsUnit.Pixel, imageAttributes);
                    }
                }
            }
            return(new RasterPatch2(
                       regionBox,
                       resultBitmap,
                       Wgs84CoordinateReferenceSystem.Instance));
        }
Beispiel #30
0
        public static HsbColor RgbToHsb(this Color rgbColor)
        {
            /* Hue values range between 0 and 360. All
             * other values range between 0 and 1. */

            // Create HSB color object
            var hsbColor = new HsbColor();

            // Get RGB color component values
            var r = Convert.ToInt32(rgbColor.R);
            var g = Convert.ToInt32(rgbColor.G);
            var b = Convert.ToInt32(rgbColor.B);
            var a = Convert.ToInt32(rgbColor.A);

            // Get min, max, and delta values
            double min   = Math.Min(Math.Min(r, g), b);
            double max   = Math.Max(Math.Max(r, g), b);
            var    delta = max - min;

            /* Black (max = 0) is a special case. We
             * simply set HSB values to zero and exit. */

            // Black: Set HSB and return
            if (max == 0.0)
            {
                hsbColor.H = 0.0;
                hsbColor.S = 0.0;
                hsbColor.B = 0.0;
                hsbColor.A = a;
                return(hsbColor);
            }

            /* Now we process the normal case. */

            // Set HSB Alpha value
            var alpha = Convert.ToDouble(a);

            hsbColor.A = alpha / 255;

            // Set HSB Hue value
            if (r == max)
            {
                hsbColor.H = (g - b) / delta;
            }
            else if (g == max)
            {
                hsbColor.H = 2 + (b - r) / delta;
            }
            else if (b == max)
            {
                hsbColor.H = 4 + (r - g) / delta;
            }
            hsbColor.H *= 60;
            if (hsbColor.H < 0.0)
            {
                hsbColor.H += 360;
            }

            // Set other HSB values
            hsbColor.S = delta / max;
            hsbColor.B = max / 255;

            // Set return value
            return(hsbColor);
        }
Beispiel #31
0
        public static Color HsbToRgb(this HsbColor hsbColor)
        {
            // Initialize
            var rgbColor = new Color();

            /* Gray (zero saturation) is a special case.We simply
            * set RGB values to HSB Brightness value and exit. */

            // Gray: Set RGB and return
            if (hsbColor.S == 0.0)
            {
                rgbColor.A = Convert.ToByte(hsbColor.A);
                rgbColor.R = Convert.ToByte(hsbColor.B * 255);
                rgbColor.G = Convert.ToByte(hsbColor.B * 255);
                rgbColor.B = Convert.ToByte(hsbColor.B * 255);
                return(rgbColor);
            }

            /* Now we process the normal case. */

            var h = hsbColor.H == 360 ? 0 : hsbColor.H / 60;
            var i = Convert.ToInt32(Math.Truncate(h));
            var f = h - i;

            var p = hsbColor.B * (1.0 - hsbColor.S);
            var q = hsbColor.B * (1.0 - hsbColor.S * f);
            var t = hsbColor.B * (1.0 - hsbColor.S * (1.0 - f));

            double r, g, b;

            switch (i)
            {
            case 0:
                r = hsbColor.B;
                g = t;
                b = p;
                break;

            case 1:
                r = q;
                g = hsbColor.B;
                b = p;
                break;

            case 2:
                r = p;
                g = hsbColor.B;
                b = t;
                break;

            case 3:
                r = p;
                g = q;
                b = hsbColor.B;
                break;

            case 4:
                r = t;
                g = p;
                b = hsbColor.B;
                break;

            default:
                r = hsbColor.B;
                g = p;
                b = q;
                break;
            }

            // Set WPF Color object
            rgbColor.A = Convert.ToByte(hsbColor.A * 255);
            rgbColor.R = Convert.ToByte(r * 255);
            rgbColor.G = Convert.ToByte(g * 255);
            rgbColor.B = Convert.ToByte(b * 255);

            // Set return value
            return(rgbColor);
        }
		protected void RebuildUI()
		{
			var time = watch.ElapsedMilliseconds;
			double dt = time - prevElapsedMilliseconds;
			prevElapsedMilliseconds = time;

			dt /= 1000;
			GetFluidData(dens_prev, u_prev, v_prev);
			VelocityStep(N, u, v, u_prev, v_prev, 0.01, dt);
			DensityStep(N, dens, dens_prev, u, v, 2.0, dt);

			double densityMin = Double.PositiveInfinity;
			double densityMax = Double.NegativeInfinity;
			for (int i = 0; i < N + 2; i++)
			{
				for (int j = 0; j < N + 2; j++)
				{
					var value = dens[i, j];
					if (value < densityMin)
						densityMin = value;
					if (value > densityMax)
						densityMax = value;
				}
			}

			int[] pixels = new int[(N + 2) * (N + 2)];

			for (int i = 0; i < N + 2; i++)
			{
				for (int j = 0; j < N + 2; j++)
				{
					double value = dens[i, N + 1 - j];
					HsbColor color = new HsbColor(10, 1, (value - densityMin) / (densityMax - densityMin));

					pixels[(N + 1 - j) * (N + 2) + i] = color.ToArgb();
				}
			}

			bmp.WritePixels(new Int32Rect(0, 0, N + 2, N + 2), pixels, ((N + 2) * PixelFormats.Bgra32.BitsPerPixel + 7) / 8, 0);
		}
		private static void GenerateWhiteNoizeImage(int width, int height, int[] pixels)
		{
			Random rnd = new Random();
			for (int i = 0; i < width * height; i++)
			{
				HsbColor color = new HsbColor(0, 0, Math.Round(5 * rnd.NextDouble()) / 4);
				int argb = color.ToArgb();
				pixels[i] = argb;
			}
		}
        /// <summary>
        /// Calculates the value this animation believes should be the current value for the property.
        /// </summary>
        /// <param name="defaultOriginValue">
        /// This value is the suggested origin value provided to the animation
        /// to be used if the animation does not have its own concept of a
        /// start value. If this animation is the first in a composition chain
        /// this value will be the snapshot value if one is available or the
        /// base property value if it is not; otherise this value will be the
        /// value returned by the previous animation in the chain with an
        /// animationClock that is not Stopped.
        /// </param>
        /// <param name="defaultDestinationValue">
        /// This value is the suggested destination value provided to the animation
        /// to be used if the animation does not have its own concept of an
        /// end value. This value will be the base value if the animation is
        /// in the first composition layer of animations on a property;
        /// otherwise this value will be the output value from the previous
        /// composition layer of animations for the property.
        /// </param>
        /// <param name="animationClock">
        /// This is the animationClock which can generate the CurrentTime or
        /// CurrentProgress value to be used by the animation to generate its
        /// output value.
        /// </param>
        /// <returns>
        /// The value this animation believes should be the current value for the property.
        /// </returns>
        protected override Color GetCurrentValueCore(
            Color defaultOriginValue,
            Color defaultDestinationValue,
            AnimationClock animationClock)
        {
            if (animationClock.CurrentState == ClockState.Stopped ||
                !animationClock.CurrentProgress.HasValue)
            {
                return(defaultOriginValue);
            }

            double          progress       = animationClock.CurrentProgress.Value;
            IEasingFunction easingFunction = EasingFunction;

            if (easingFunction != null)
            {
                progress = easingFunction.Ease(progress);
            }

            if (progress.IsLessThan(0) ||
                progress.IsGreaterThan(1))
            {
                return(defaultOriginValue);
            }

            // Need to double the pace if reverse effect is enabled
            float scaleFactor = (float)(reverseEffect ? progress * 2 : progress);

            float hueDelta        = hueOffset;
            float saturationDelta = saturationOffset;
            float brightnessDelta = brightnessOffset;

            if (!reverseEffect ||
                scaleFactor.IsLessThanOrClose(1))
            {
                hueDelta        *= scaleFactor;
                saturationDelta *= scaleFactor;
                brightnessDelta *= scaleFactor;
            }
            else
            {
                if (scaleFactor.IsGreaterThan(1))
                {
                    scaleFactor -= 1;

                    hueDelta        -= hueDelta * scaleFactor;
                    saturationDelta -= saturationDelta * scaleFactor;
                    brightnessDelta -= brightnessDelta * scaleFactor;
                }
            }

            if (hueDelta.IsZero() &&
                saturationDelta.IsZero() &&
                brightnessDelta.IsZero())
            {
                // No changes
                return(defaultOriginValue);
            }

            Color color = HsbColor.Offset(
                defaultDestinationValue,
                hueDelta,
                saturationDelta,
                brightnessDelta);

            return(color);
        }
Beispiel #35
0
        /// <summary>
        /// Converts an HSB color to an RGB color.
        /// </summary>
        /// <param name="hsbColor">The HSB color to convert.</param>
        /// <returns>The RGB color equivalent of the HSB color passed in.</returns>
        /// Source: http://msdn.microsoft.com/en-us/library/ms771620.aspx
        public static Color HsbToRgb(HsbColor hsbColor)
        {
            // Initialize
            var rgbColor = new Color();

            /* Gray (zero saturation) is a special case.We simply
             * set RGB values to HSB Brightness value and exit. */

            // Gray: Set RGB and return
            if (hsbColor.S == 0.0)
            {
                rgbColor.A = (byte)(hsbColor.A * 255);
                rgbColor.R = (byte)(hsbColor.B * 255);
                rgbColor.G = (byte)(hsbColor.B * 255);
                rgbColor.B = (byte)(hsbColor.B * 255);
                return rgbColor;
            }

            /* Now we process the normal case. */

            var h = (hsbColor.H == 360) ? 0 : hsbColor.H / 60;
            var i = (int)(Math.Truncate(h));
            var f = h - i;

            var p = hsbColor.B * (1.0 - hsbColor.S);
            var q = hsbColor.B * (1.0 - (hsbColor.S * f));
            var t = hsbColor.B * (1.0 - (hsbColor.S * (1.0 - f)));

            double r, g, b;
            switch (i)
            {
                case 0:
                    r = hsbColor.B;
                    g = t;
                    b = p;
                    break;

                case 1:
                    r = q;
                    g = hsbColor.B;
                    b = p;
                    break;

                case 2:
                    r = p;
                    g = hsbColor.B;
                    b = t;
                    break;

                case 3:
                    r = p;
                    g = q;
                    b = hsbColor.B;
                    break;

                case 4:
                    r = t;
                    g = p;
                    b = hsbColor.B;
                    break;

                default:
                    r = hsbColor.B;
                    g = p;
                    b = q;
                    break;
            }

            // Set WPF Color object
            rgbColor.A = (byte)(hsbColor.A * 255);
            rgbColor.R = (byte)(r * 255);
            rgbColor.G = (byte)(g * 255);
            rgbColor.B = (byte)(b * 255);

            // Set return value
            return rgbColor;
        }
Beispiel #36
0
 private void updateHsbColor()
 {
     hsb = new HsbColor(selectedColor);
 }
Beispiel #37
0
 public static Color GetRgb(HsbColor hsb)
 {
     HsbToRgb(hsb.Hue, hsb.Saturation / 100.0, hsb.Brightness / 100.0, out var r, out var g, out var b);
     return(Color.FromArgb(255, (byte)r, (byte)g, (byte)b));
 }