Beispiel #1
0
        private void UpdateRGB(float h, float s, float v)
        {
            var col = SKColor.FromHsl(h, s, v);

            _red   = col.Red;
            _green = col.Green;
            _blue  = col.Blue;
        }
        public override object Apply(object currentValue, object parameterValue)
        {
            ((SKColor)currentValue).ToHsl(out float h, out float s, out float l);

            h += (float)parameterValue;

            return(SKColor.FromHsl(h % 360, s, l));
        }
        public ColorWheelPopup()
        {
            InitializeComponent();

            for (int i = 0; i < _colors.Length; i++)
            {
                _colors[i] = SKColor.FromHsl(i * 360f / 7, 100, 50);
            }
        }
Beispiel #4
0
    public void HslColor()
    {
        using var img = GenericVisualizer.RenderPalette(
                  new Size(10, 10),
                  pos => SKColor.FromHsl(0, 100 * (pos.X / 10f), 100 * (pos.Y / 10f)),
                  scale: 20);

        Save(img, "HSL with Saturation x Luminosity");
    }
        private void OnHslCanvasViewPaintSurface(object sender, SkiaSharp.Views.Forms.SKPaintSurfaceEventArgs e)
        {
            SKColor color = SKColor.FromHsl((float)hueSlider.Value,
                                            (float)saturationSlider.Value, (float)lightnessSlider.Value);

            e.Surface.Canvas.Clear();

            hslLabel.Text = String.Format("RGB = {0:X2}-{1:X2}-{2:X2} ", color.Red, color.Green, color.Blue);
        }
Beispiel #6
0
        /// <summary>
        /// Gernerates colors out of an integer.
        /// </summary>
        public static List <SKColor> GenerateColors(int n)
        {
            List <SKColor> colors = new List <SKColor>();

            for (int i = 0; i < n; i++)
            {
                colors.Add(SKColor.FromHsl(360 * (i + 1) / n, 65, 50));
            }
            return(colors);
        }
Beispiel #7
0
 private SKColor GetNewColor(int n)
 {
     var rnd = new Random(n*10);
     
     _BrushInfoService.StrokeColor.ToHsl(out float h, out float s, out float v);
     h = (h + _BrushInfoService.HueDispersion * (rnd.NextDouble().ToFloat() - 0.5F)).ToDouble().FixAngleDegrees().ToFloat();
     s = Clamp(s + _BrushInfoService.SaturationDispersion * (rnd.NextDouble().ToFloat() - 0.5F), 0, 100);
     v = Clamp(v + _BrushInfoService.SaturationDispersion * (rnd.NextDouble().ToFloat() - 0.5F), 0, 100);
     SKColor col = SKColor.FromHsl(h, s, v);
     return col;
 }
Beispiel #8
0
        private void CanvasPaintSurface(object sender, SKPaintGLSurfaceEventArgs e)
        {
            var canvas = e.Surface.Canvas;
            var rect   = e.BackendRenderTarget.Rect;
            var radius = rect.Height / 2;

            canvas.Clear(SKColors.White);

            var ProgessColor = new SKPaint
            {
                IsAntialias = true,
                Style       = SKPaintStyle.StrokeAndFill,
                Color       = SKColor.FromHsl(202f, 78.3f, 45.1f),
                StrokeWidth = 1
            };

            var BgColor = new SKPaint
            {
                IsAntialias = true,
                Style       = SKPaintStyle.StrokeAndFill,
                Color       = SKColor.FromHsl(0f, 0f, 93.3f),
                StrokeWidth = 1
            };

            var TextColor = new SKPaint
            {
                IsAntialias  = true,
                FakeBoldText = true,
                Style        = SKPaintStyle.Fill,
                Color        = SKColors.Black,
                TextSize     = radius,
                TextAlign    = SKTextAlign.Left
            };


            canvas.DrawRect(new SKRect(radius, 0, rect.Width - radius, rect.Height), BgColor);
            canvas.DrawCircle(radius, radius, radius, BgColor);
            canvas.DrawCircle(rect.Width - radius, radius, radius, BgColor);

            var width = rect.Width - 2 * radius;

            var val = (int)(width * Sld.Value);

            canvas.DrawRect(new SKRect(radius, 0, radius + val, rect.Height), ProgessColor);
            canvas.DrawCircle(radius, radius, radius, ProgessColor);
            canvas.DrawCircle(radius + val, radius, radius, ProgessColor);

            canvas.DrawText(string.Format("${0:0.00}", 100 * Sld.Value), radius, 1.5f * radius, TextColor);

            ProgessColor.Dispose();
            BgColor.Dispose();
            TextColor.Dispose();
        }
        void DrawRange(SKCanvas canvas, int width, int height, float degreesOffset, int steps,
                       Func <int, int, float> calcStepSide, float value, bool drawColorValuesAsText = false)
        {
            var degreesStep = 360f / steps;
            var halfWidth   = width / 2f;
            var halfHeight  = height / 2f;
            var stepSide    = calcStepSide(width, height);
            var scale       = width / (float)canvasView.Width;
            var textBrush   = new SKPaint
            {
                IsAntialias = true,
                Style       = SKPaintStyle.Fill,
                Color       = SKColors.White,
                TextSize    = 10 * scale
            };
            var arcRect = new SKRect(halfWidth - stepSide, halfHeight - stepSide,
                                     halfWidth + stepSide, halfHeight + stepSide);

            for (var i = 0; i < steps; i++)
            {
                var degrees           = i * degreesStep;
                var degreesWithOffset = degrees + degreesOffset;
                var brush             = new SKPaint
                {
                    IsAntialias = true,
                    Style       = SKPaintStyle.Fill,
                    Color       = hslOrHsvEnabled ?
                                  SKColor.FromHsl(degrees, 100, value, 255) :
                                  SKColor.FromHsv(degrees, 100, value, 255)
                };

                canvas.RotateDegrees(degreesWithOffset, halfWidth, halfHeight);
                using (var path = new SKPath())
                {
                    path.MoveTo(halfWidth, halfHeight);
                    //path.LineTo(halfWidth, halfHeight - stepSide);
                    //path.LineTo(halfWidth + (float)Math.Tan((Math.PI / 180) * degreesStep) * stepSide, halfHeight - stepSide);
                    path.ArcTo(arcRect, 270, degreesStep, false);
                    path.Close();
                    canvas.DrawPath(path, brush);
                }

                if (drawColorValuesAsText)
                {
                    var textX = halfWidth;
                    var textY = halfHeight - 3 * (stepSide / 4);
                    canvas.DrawText(brush.Color.ToString(), textX, textY, textBrush);
                }

                canvas.RotateDegrees(-degreesWithOffset, halfWidth, halfHeight);
            }
        }
Beispiel #10
0
        public static SKColor InsertColor(Color start, Color end, double percent)
        {
            start.ToSKColor().ToHsl(out float sh, out float ss, out float sl);

            end.ToSKColor().ToHsl(out float eh, out float es, out float el);

            float newH = (sh - eh) * (float)percent + eh;

            float newS = (ss - es) * (float)percent + es;

            float newL = (sl - el) * (float)percent + el;

            return(SKColor.FromHsl(newH, newS, newL));
        }
Beispiel #11
0
        SKColor TemperatureColor(float v)
        {
            if (v > 35)
            {
                v = 35;
            }
            else if (v < 15)
            {
                v = 15;
            }
            var hue = 270 * (35 - v) / 20;

            return(SKColor.FromHsl(hue, 100, 50));
        }
Beispiel #12
0
        public async Task <JObject> FunctionHandlerAsync(ImageInfo imageInfo, ILambdaContext context)
        {
            var dowloadedImagePath = await _s3Service.GetImageFromS3($"{imageInfo.UserId}/pictures/original/single/{imageInfo.ImageFileName}", imageInfo.ImageFileName);

            var newFileName = imageInfo.ImageFileName.Remove(imageInfo.ImageFileName.Length - 4, 4);

            newFileName = newFileName + "_simpleBinarization.jpg";

            using (var input = File.OpenRead(dowloadedImagePath))
            {
                using (var inputStream = new SKManagedStream(input))
                {
                    using (var original = SKBitmap.Decode(inputStream))
                    {
                        for (int i = 0; i < original.Width - 1; i++)
                        {
                            for (int j = 0; j < original.Height - 1; j++)
                            {
                                SKColor pixelColor = original.GetPixel(i, j);

                                int ret = (int)(pixelColor.Red * 0.299f + pixelColor.Green * 0.578f + pixelColor.Blue * 0.114f);

                                if (ret > 50)
                                {
                                    original.SetPixel(i, j, SKColor.FromHsl(0.0f, 0.0f, 100.0f));
                                }
                                else
                                {
                                    original.SetPixel(i, j, SKColor.FromHsl(0.0f, 0.0f, 0.0f));
                                }
                            }
                        }

                        using (var image = SKImage.FromBitmap(original))
                        {
                            using (var output = File.OpenWrite($"/tmp/{newFileName}"))
                            {
                                image.Encode(SKEncodedImageFormat.Jpeg, 75)
                                .SaveTo(output);
                            }
                        }
                    }
                }
            }
            var key    = $"{imageInfo.UserId}/pictures/binarization/simple/csharp/{newFileName}";
            var status = await _s3Service.PutImageToS3(key, $"/tmp/{newFileName}");

            return(JObject.FromObject(new { StatusCode = status, Body = key }));
        }
Beispiel #13
0
        void SetColors()
        {
            SKColor[] colors = new SKColor[_maxIterations];

            _colors.CopyTo(colors, 0);

            Random rand = new Random(DateTime.Now.Millisecond);

            for (long i = _colors.LongLength; i < _maxIterations; ++i)
            {
                colors[i] = SKColor.FromHsl((float)rand.NextDouble() * 360, 255, 255);
            }

            _colors = colors;
        }
        void OnSliderValueChanged(object sender, ValueChangedEventArgs e)
        {
            // Calculate new color based on sliders
            color = SKColor.FromHsl((float)hueSlider.Value,
                                    (float)satSlider.Value,
                                    (float)lumSlider.Value);

            // Use labels to display HSL and RGB color values
            color.ToHsl(out float hue, out float sat, out float lum);

            hslLabel.Text = String.Format("HSL = {0:F0} {1:F0} {2:F0}",
                                          hue, sat, lum);

            rgbLabel.Text = String.Format("RGB = {0:X2} {1:X2} {2:X2}",
                                          color.Red, color.Green, color.Blue);

            canvasView.InvalidateSurface();
        }
Beispiel #15
0
        public void ActivateOrbitingStars(float screenWidth, float screenHeight)
        {
            Random randomizer = new Random();

            for (int i = 0; i < 30; i++)
            {
                OrbitingStarParticle star = new OrbitingStarParticle(randomizer.Next((int)screenWidth) + screenWidth / 2,
                                                                     randomizer.Next((int)screenHeight) + screenHeight / 2,
                                                                     Radius / 4,
                                                                     randomizer,
                                                                     SKColor.FromHsl(21, 78, randomizer.Next(0, 6))
                                                                     );
                //OrbitingStarParticle star = new OrbitingStarParticle(randomizer.Next((int)screenWidth) - screenWidth / 2, randomizer.Next((int)screenHeight) - screenHeight / 2, Radius / 4, randomizer, CreateColor(0, 0, 0));
                star.SetTarget(0, 0);
                AddChild(star);
                _listOfStarParticles.Add(star);
                star.SteerToTarget();
            }
        }
        void OnCanvasViewPaintSurface(object sender, SKPaintSurfaceEventArgs args)
        {
            SKImageInfo info    = args.Info;
            SKSurface   surface = args.Surface;
            SKCanvas    canvas  = surface.Canvas;

            canvas.Clear();

            using (SKPaint paint = new SKPaint())
            {
                float rainbowWidth = Math.Min(info.Width, info.Height) / 4f;

                // Center of arc and gradient is lower-right corner
                SKPoint center = new SKPoint(info.Width, info.Height);

                // Find outer, inner, and middle radius
                float outerRadius = Math.Min(info.Width, info.Height);
                float innerRadius = outerRadius - rainbowWidth;
                float radius      = outerRadius - rainbowWidth / 2;

                // Calculate the colors and positions
                SKColor[] colors    = new SKColor[8];
                float[]   positions = new float[8];

                for (int i = 0; i < colors.Length; i++)
                {
                    colors[i]    = SKColor.FromHsl(i * 360f / 7, 100, 50);
                    positions[i] = (i + (7f - i) * innerRadius / outerRadius) / 7f;
                }

                // Create sweep gradient based on center and outer radius
                paint.Shader = SKShader.CreateRadialGradient(center,
                                                             outerRadius,
                                                             colors,
                                                             positions,
                                                             SKShaderTileMode.Clamp);
                // Draw a circle with a wide line
                paint.Style       = SKPaintStyle.Stroke;
                paint.StrokeWidth = rainbowWidth;

                canvas.DrawCircle(center, radius, paint);
            }
        }
Beispiel #17
0
        static void Main(string[] args)
        {
            Directory.CreateDirectory("output");

            var content = "testtesttest";

            using (var generator = new QRCodeGenerator())
            {
                // Generate QrCode
                var qr = generator.CreateQrCode(content, ECCLevel.L);

                // Render to canvas
                var info = new SKImageInfo(512, 512);
                using (var surface = SKSurface.Create(info))
                {
                    var canvas = surface.Canvas;
                    canvas.Render(qr, info.Width, info.Height);

                    // gen color
                    // yellow https://rgb.to/yellow
                    canvas.Render(qr, info.Width, info.Height, SKColor.Empty, SKColor.FromHsl(60, 100, 50));
                    // red https://rgb.to/red
                    canvas.Render(qr, info.Width, info.Height, SKColor.Empty, SKColor.FromHsl(0, 100, 50));

                    // gen icon
                    var logo = File.ReadAllBytes("samples/test.png");
                    var icon = new IconData
                    {
                        Icon            = SKBitmap.Decode(logo),
                        IconSizePercent = 10,
                    };
                    canvas.Render(qr, info.Width, info.Height, SKColor.Empty, SKColor.Parse("000000"), icon);

                    // Output to Stream -> File
                    using (var image = surface.Snapshot())
                        using (var data = image.Encode(SKEncodedImageFormat.Png, 100))
                            using (var stream = File.OpenWrite(@"output/hoge.png"))
                            {
                                data.SaveTo(stream);
                            }
                }
            }
        }
Beispiel #18
0
        public override void Render(IDrawingContextImpl context)
        {
            // converts the impl to SKCanvas
            var canvas = (context as ISkiaDrawingContextImpl)?.SkCanvas;

            //Checks if that is valid
            if (canvas == null)
            {
                //context.DrawText(new SolidColorBrush(Colors.Black), new Point(), NoSkia);
            }
            else // when it's valid to this
            {
                var info = new SKImageInfo((int)Bounds.Width, (int)Bounds.Height); // creates the image info
                canvas.RotateDegrees(-90, (float)Bounds.Center.X, (float)Bounds.Center.Y);

                using (SKPaint paint = new SKPaint()) // creates the paint
                {
                    // Define an array of rainbow colors
                    SKColor[] colors = new SKColor[8];

                    for (int i = 0; i < colors.Length; i++)
                    {
                        colors[i] = SKColor.FromHsl(i * 360f / 7, 100, 50); //sets the colors
                    }

                    SKPoint center = new SKPoint(info.Rect.MidX, info.Rect.MidY); // creates the center

                    paint.IsAntialias = true;

                    // Create sweep gradient based on center of canvas
                    paint.Shader = SKShader.CreateSweepGradient(center, colors, null);

                    // Draw a circle with a wide line
                    paint.Style       = SKPaintStyle.Stroke;
                    paint.StrokeWidth = StrokeWidth;

                    float radius = (Math.Min(info.Width, info.Height) - StrokeWidth) / 2; //computes the radius
                    canvas.DrawCircle(center, radius, paint);                             // draw a circle with its respects parameters
                }
            }
        }
Beispiel #19
0
        void OnCanvasViewPaintSurface(object sender, SKPaintSurfaceEventArgs args)
        {
            SKImageInfo info    = args.Info;
            SKSurface   surface = args.Surface;
            SKCanvas    canvas  = surface.Canvas;

            canvas.Clear();
            canvas.Translate(info.Width / 2, info.Height / 2);
            float radius = (float)Math.Min(info.Width, info.Height) / 2 - 100;

            using (SKPaint paint = new SKPaint())
            {
                paint.Style = SKPaintStyle.Fill;
                paint.Color = SKColor.FromHsl(angle, 100, 50);

                float x = radius * (float)Math.Sin(Math.PI * angle / 180);
                float y = -radius * (float)Math.Cos(Math.PI * angle / 180);
                canvas.Translate(x, y);
                canvas.DrawPath(HendecagramArrayPage.HendecagramPath, paint);
            }
        }
Beispiel #20
0
        void OnCanvasViewPaintSurface(object sender, SKPaintSurfaceEventArgs args)
        {
            SKImageInfo info    = args.Info;
            SKSurface   surface = args.Surface;
            SKCanvas    canvas  = surface.Canvas;

            canvas.Clear();

            using (SKPaint paint = new SKPaint())
            {
                // Define an array of rainbow colors
                SKColor[] colors = new SKColor[8];

                for (int i = 0; i < colors.Length; i++)
                {
                    colors[i] = SKColor.FromHsl(i * 360f / 7, 100, 50);
                }

                SKPoint center = new SKPoint(info.Rect.MidX, info.Rect.MidY);

                // Create sweep gradient based on center of canvas
                paint.Shader = SKShader.CreateSweepGradient(center, colors, null);

                // Draw a circle with a wide line
                const int strokeWidth = 50;
                paint.Style       = SKPaintStyle.Stroke;
                paint.StrokeWidth = strokeWidth;

                float radius = (Math.Min(info.Width, info.Height) - strokeWidth) / 2;
                canvas.DrawCircle(center, radius, paint);

                if (drawBackground)
                {
                    // Draw the gradient on the whole canvas
                    paint.Style = SKPaintStyle.Fill;
                    canvas.DrawRect(info.Rect, paint);
                }
            }
        }
Beispiel #21
0
        public Header()
        {
            if (Properties.Settings.Default.UseChallengeBanner)
            {
                SKColor mainColor = SKColor.Parse(Properties.Settings.Default.ChallengeBannerPrimaryColor);
                mainColor.ToHsl(out float h, out float s, out float l);
                float i = l + 20.0F > 100.0F ? 100.0F - l : 20.0F;

                PrimaryColor   = mainColor;
                SecondaryColor = SKColor.Parse(Properties.Settings.Default.ChallengeBannerSecondaryColor);
                AccentColor    = SKColor.FromHsl(h += i, s, l);
                DisplayImage   = null;
                if (!string.IsNullOrEmpty(Properties.Settings.Default.ChallengeBannerPath))
                {
                    CustomBackground = SKBitmap.Decode(new FileInfo(Properties.Settings.Default.ChallengeBannerPath).Open(FileMode.Open, FileAccess.Read, FileShare.ReadWrite));
                }
                else
                {
                    CustomBackground = null;
                }
            }
            else
            {
                SKColor mainColor = SKColor.Parse(_randomColors[_random.Next(0, 255)]);
                mainColor.ToHsl(out float h, out float s, out float l);
                while (l > 75 || l < 10)
                {
                    mainColor = SKColor.Parse(_randomColors[_random.Next(0, 255)]);
                    mainColor.ToHsl(out float _, out float _, out l);
                }
                float i = l + 20.0F > 100.0F ? 100.0F - l : 20.0F;

                PrimaryColor     = mainColor;
                SecondaryColor   = SKColor.FromHsl(h, s, l += i);
                AccentColor      = SKColor.FromHsl(h += i, s, l);
                DisplayImage     = null;
                CustomBackground = null;
            }
        }
Beispiel #22
0
        public RainbowSinePage()
        {
            Title = "Rainbow Sine";

            bitmap = new SKBitmap(360 * 3, 1024, SKColorType.Bgra8888, SKAlphaType.Unpremul);

            unsafe
            {
                // Pointer to first pixel of bitmap
                uint *basePtr = (uint *)bitmap.GetPixels().ToPointer();

                // Loop through the rows
                for (int row = 0; row < bitmap.Height; row++)
                {
                    // Calculate the sine curve angle and the sine value
                    double angle = 2 * Math.PI * row / bitmap.Height;
                    double sine  = Math.Sin(angle);

                    // Loop through the hues
                    for (int hue = 0; hue < 360; hue++)
                    {
                        // Calculate the column
                        int col = (int)(360 + 360 * sine + hue);

                        // Calculate the address
                        uint *ptr = basePtr + bitmap.Width * row + col;

                        // Store the color value
                        *ptr = (uint)SKColor.FromHsl(hue, 100, 50);
                    }
                }
            }

            // Create the SKCanvasView
            SKCanvasView canvasView = new SKCanvasView();

            canvasView.PaintSurface += OnCanvasViewPaintSurface;
            Content = canvasView;
        }
Beispiel #23
0
        public void ColorRgbToHsl()
        {
            var tuples = new List <ToOtherColor> {
                new ToOtherColor(new SKColor(000, 000, 000), new SKOtherColor(000f, 000.0f, 000.0f), "Black"),
                new ToOtherColor(new SKColor(255, 000, 000), new SKOtherColor(000f, 100.0f, 050.0f), "Red"),
                new ToOtherColor(new SKColor(255, 255, 000), new SKOtherColor(060f, 100.0f, 050.0f), "Yellow"),
                new ToOtherColor(new SKColor(255, 255, 255), new SKOtherColor(000f, 000.0f, 100.0f), "White"),
                new ToOtherColor(new SKColor(128, 128, 128), new SKOtherColor(000f, 000.0f, 050.2f), "Gray"),
                new ToOtherColor(new SKColor(128, 128, 000), new SKOtherColor(060f, 100.0f, 025.1f), "Olive"),
                new ToOtherColor(new SKColor(000, 128, 000), new SKOtherColor(120f, 100.0f, 025.1f), "Green"),
                new ToOtherColor(new SKColor(000, 000, 128), new SKOtherColor(240f, 100.0f, 025.1f), "Navy"),
            };

            foreach (var item in tuples)
            {
                // values
                SKColor      rgb   = item.Item1;
                SKOtherColor other = item.Item2;

                // to HSL
                float h, s, l;
                rgb.ToHsl(out h, out s, out l);

                Assert.AreEqual(other.Item1, h, EPSILON, item.Item3 + " H");
                Assert.AreEqual(other.Item2, s, EPSILON, item.Item3 + " S");
                Assert.AreEqual(other.Item3, l, EPSILON, item.Item3 + " L");

                // to RGB
                SKColor back = SKColor.FromHsl(other.Item1, other.Item2, other.Item3);

                Assert.AreEqual(rgb.Red, back.Red, item.Item3 + " R");
                Assert.AreEqual(rgb.Green, back.Green, item.Item3 + " G");
                Assert.AreEqual(rgb.Blue, back.Blue, item.Item3 + " B");
                Assert.AreEqual(rgb.Alpha, back.Alpha, item.Item3 + " A");
            }
        }
Beispiel #24
0
        /// <param name="value">The value to convert.</param>
        /// <summary>Creates a color from a valid color name.</summary>
        /// <returns>To be added.</returns>
        /// <remarks>To be added.</remarks>
        public override object ConvertFromInvariantString(string value)
        {
            if (value != null)
            {
                value = value.Trim();
                if (value.StartsWith("#", StringComparison.Ordinal))
                {
                    return(FromHex(value));
                }
                if (value.StartsWith("rgba", StringComparison.OrdinalIgnoreCase))
                {
                    int op = value.IndexOf('(');
                    int cp = value.LastIndexOf(')');
                    if (op < 0 || cp < 0 || cp < op)
                    {
                        throw new InvalidOperationException(string.Format("Cannot convert \"{0}\" into {1}", new object[]
                        {
                            value,
                            typeof(SKColor)
                        }));
                    }
                    string[] quad = value.Substring(op + 1, cp - op - 1).Split(new char[]
                    {
                        ','
                    });
                    if (quad.Length != 4)
                    {
                        throw new InvalidOperationException(string.Format("Cannot convert \"{0}\" into {1}", new object[]
                        {
                            value,
                            typeof(SKColor)
                        }));
                    }
                    byte r = SKColorTypeConverter.ParseColorValue(quad[0], byte.MaxValue, true);
                    byte g = SKColorTypeConverter.ParseColorValue(quad[1], byte.MaxValue, true);
                    byte b = SKColorTypeConverter.ParseColorValue(quad[2], byte.MaxValue, true);
                    byte a = SKColorTypeConverter.ParseOpacity(quad[3]);
                    return(new SKColor(r, g, b, a));
                }
                else if (value.StartsWith("rgb", StringComparison.OrdinalIgnoreCase))
                {
                    int op2 = value.IndexOf('(');
                    int cp2 = value.LastIndexOf(')');
                    if (op2 < 0 || cp2 < 0 || cp2 < op2)
                    {
                        throw new InvalidOperationException(string.Format("Cannot convert \"{0}\" into {1}", new object[]
                        {
                            value,
                            typeof(SKColor)
                        }));
                    }
                    string[] triplet = value.Substring(op2 + 1, cp2 - op2 - 1).Split(new char[]
                    {
                        ','
                    });
                    if (triplet.Length != 3)
                    {
                        throw new InvalidOperationException(string.Format("Cannot convert \"{0}\" into {1}", new object[]
                        {
                            value,
                            typeof(SKColor)
                        }));
                    }
                    byte r2 = SKColorTypeConverter.ParseColorValue(triplet[0], byte.MaxValue, true);
                    byte g2 = SKColorTypeConverter.ParseColorValue(triplet[1], byte.MaxValue, true);
                    byte b2 = SKColorTypeConverter.ParseColorValue(triplet[2], byte.MaxValue, true);
                    return(new SKColor(r2, g2, b2));
                }
                else if (value.StartsWith("hsla", StringComparison.OrdinalIgnoreCase))
                {
                    int op3 = value.IndexOf('(');
                    int cp3 = value.LastIndexOf(')');
                    if (op3 < 0 || cp3 < 0 || cp3 < op3)
                    {
                        throw new InvalidOperationException(string.Format("Cannot convert \"{0}\" into {1}", new object[]
                        {
                            value,
                            typeof(Color)
                        }));
                    }
                    string[] quad2 = value.Substring(op3 + 1, cp3 - op3 - 1).Split(new char[]
                    {
                        ','
                    });
                    if (quad2.Length != 4)
                    {
                        throw new InvalidOperationException(string.Format("Cannot convert \"{0}\" into {1}", new object[]
                        {
                            value,
                            typeof(Color)
                        }));
                    }
                    float h  = SKColorTypeConverter.ParseColorValue(quad2[0], 360, false);
                    float s  = SKColorTypeConverter.ParseColorValue(quad2[1], 100, true);
                    float i  = SKColorTypeConverter.ParseColorValue(quad2[2], 100, true);
                    byte  a2 = SKColorTypeConverter.ParseOpacity(quad2[3]);
                    return(SKColor.FromHsl(h, s, i, a2));
                }
                else if (value.StartsWith("hsl", StringComparison.OrdinalIgnoreCase))
                {
                    int op4 = value.IndexOf('(');
                    int cp4 = value.LastIndexOf(')');
                    if (op4 < 0 || cp4 < 0 || cp4 < op4)
                    {
                        throw new InvalidOperationException(string.Format("Cannot convert \"{0}\" into {1}", new object[]
                        {
                            value,
                            typeof(Color)
                        }));
                    }
                    string[] triplet2 = value.Substring(op4 + 1, cp4 - op4 - 1).Split(new char[]
                    {
                        ','
                    });
                    if (triplet2.Length != 3)
                    {
                        throw new InvalidOperationException(string.Format("Cannot convert \"{0}\" into {1}", new object[]
                        {
                            value,
                            typeof(Color)
                        }));
                    }
                    float h2 = SKColorTypeConverter.ParseColorValue(triplet2[0], 360, false);
                    float s2 = SKColorTypeConverter.ParseColorValue(triplet2[1], 100, true);
                    float j  = SKColorTypeConverter.ParseColorValue(triplet2[2], 100, true);
                    return(SKColor.FromHsl(h2, s2, j));
                }
                else
                {
                    string[] parts = value.Split('.');
                    if (parts.Length == 1 || (parts.Length == 2 && parts[0] == "Color"))
                    {
                        string color = parts[parts.Length - 1];
                        switch (color.ToLowerInvariant())
                        {
                        case "empty": return(SKColor.Empty);

                        case "aliceblue": return(SKColors.AliceBlue);

                        case "antiquewhite": return(SKColors.AntiqueWhite);

                        case "aqua": return(SKColors.Aqua);

                        case "aquamarine": return(SKColors.Aquamarine);

                        case "azure": return(SKColors.Azure);

                        case "beige": return(SKColors.Beige);

                        case "bisque": return(SKColors.Bisque);

                        case "black": return(SKColors.Black);

                        case "blanchedalmond": return(SKColors.BlanchedAlmond);

                        case "blue": return(SKColors.Blue);

                        case "blueViolet": return(SKColors.BlueViolet);

                        case "brown": return(SKColors.Brown);

                        case "burlywood": return(SKColors.BurlyWood);

                        case "cadetblue": return(SKColors.CadetBlue);

                        case "chartreuse": return(SKColors.Chartreuse);

                        case "chocolate": return(SKColors.Chocolate);

                        case "coral": return(SKColors.Coral);

                        case "cornflowerblue": return(SKColors.CornflowerBlue);

                        case "cornsilk": return(SKColors.Cornsilk);

                        case "crimson": return(SKColors.Crimson);

                        case "cyan": return(SKColors.Cyan);

                        case "darkblue": return(SKColors.DarkBlue);

                        case "darkcyan": return(SKColors.DarkCyan);

                        case "darkgoldenrod": return(SKColors.DarkGoldenrod);

                        case "darkgray": return(SKColors.DarkGray);

                        case "darkgreen": return(SKColors.DarkGreen);

                        case "darkkhaki": return(SKColors.DarkKhaki);

                        case "darkmagenta": return(SKColors.DarkMagenta);

                        case "darkolivegreen": return(SKColors.DarkOliveGreen);

                        case "darkorange": return(SKColors.DarkOrange);

                        case "darkorchid": return(SKColors.DarkOrchid);

                        case "darkred": return(SKColors.DarkRed);

                        case "darksalmon": return(SKColors.DarkSalmon);

                        case "darkseagreen": return(SKColors.DarkSeaGreen);

                        case "darkslateblue": return(SKColors.DarkSlateBlue);

                        case "darkslategray": return(SKColors.DarkSlateGray);

                        case "darkturquoise": return(SKColors.DarkTurquoise);

                        case "darkviolet": return(SKColors.DarkViolet);

                        case "deeppink": return(SKColors.DeepPink);

                        case "deepskyblue": return(SKColors.DeepSkyBlue);

                        case "dimgray": return(SKColors.DimGray);

                        case "dodgerblue": return(SKColors.DodgerBlue);

                        case "firebrick": return(SKColors.Firebrick);

                        case "floralwhite": return(SKColors.FloralWhite);

                        case "forestgreen": return(SKColors.ForestGreen);

                        case "fuchsia": return(SKColors.Fuchsia);

                        case "gainsboro": return(SKColors.Gainsboro);

                        case "ghostwhite": return(SKColors.GhostWhite);

                        case "gold": return(SKColors.Gold);

                        case "goldenrod": return(SKColors.Goldenrod);

                        case "gray": return(SKColors.Gray);

                        case "green": return(SKColors.Green);

                        case "greenyellow": return(SKColors.GreenYellow);

                        case "honeydew": return(SKColors.Honeydew);

                        case "hotpink": return(SKColors.HotPink);

                        case "indianred": return(SKColors.IndianRed);

                        case "indigo": return(SKColors.Indigo);

                        case "ivory": return(SKColors.Ivory);

                        case "khaki": return(SKColors.Khaki);

                        case "lavender": return(SKColors.Lavender);

                        case "lavenderblush": return(SKColors.LavenderBlush);

                        case "lawngreen": return(SKColors.LawnGreen);

                        case "lemonchiffon": return(SKColors.LemonChiffon);

                        case "lightblue": return(SKColors.LightBlue);

                        case "lightcoral": return(SKColors.LightCoral);

                        case "lightcyan": return(SKColors.LightCyan);

                        case "lightgoldenrodyellow": return(SKColors.LightGoldenrodYellow);

                        case "lightgray": return(SKColors.LightGray);

                        case "lightgreen": return(SKColors.LightGreen);

                        case "lightpink": return(SKColors.LightPink);

                        case "lightsalmon": return(SKColors.LightSalmon);

                        case "lightseagreen": return(SKColors.LightSeaGreen);

                        case "lightskyblue": return(SKColors.LightSkyBlue);

                        case "lightslategray": return(SKColors.LightSlateGray);

                        case "lightsteelblue": return(SKColors.LightSteelBlue);

                        case "lightyellow": return(SKColors.LightYellow);

                        case "lime": return(SKColors.Lime);

                        case "limegreen": return(SKColors.LimeGreen);

                        case "linen": return(SKColors.Linen);

                        case "magenta": return(SKColors.Magenta);

                        case "maroon": return(SKColors.Maroon);

                        case "mediumaquamarine": return(SKColors.MediumAquamarine);

                        case "mediumblue": return(SKColors.MediumBlue);

                        case "mediumorchid": return(SKColors.MediumOrchid);

                        case "mediumpurple": return(SKColors.MediumPurple);

                        case "mediumseagreen": return(SKColors.MediumSeaGreen);

                        case "mediumslateblue": return(SKColors.MediumSlateBlue);

                        case "mediumspringgreen": return(SKColors.MediumSpringGreen);

                        case "mediumturquoise": return(SKColors.MediumTurquoise);

                        case "mediumvioletred": return(SKColors.MediumVioletRed);

                        case "midnightblue": return(SKColors.MidnightBlue);

                        case "mintcream": return(SKColors.MintCream);

                        case "mistyrose": return(SKColors.MistyRose);

                        case "moccasin": return(SKColors.Moccasin);

                        case "navajowhite": return(SKColors.NavajoWhite);

                        case "navy": return(SKColors.Navy);

                        case "oldlace": return(SKColors.OldLace);

                        case "olive": return(SKColors.Olive);

                        case "olivedrab": return(SKColors.OliveDrab);

                        case "orange": return(SKColors.Orange);

                        case "orangered": return(SKColors.OrangeRed);

                        case "orchid": return(SKColors.Orchid);

                        case "palegoldenrod": return(SKColors.PaleGoldenrod);

                        case "palegreen": return(SKColors.PaleGreen);

                        case "paleturquoise": return(SKColors.PaleTurquoise);

                        case "palevioletred": return(SKColors.PaleVioletRed);

                        case "papayawhip": return(SKColors.PapayaWhip);

                        case "peachpuff": return(SKColors.PeachPuff);

                        case "peru": return(SKColors.Peru);

                        case "pink": return(SKColors.Pink);

                        case "plum": return(SKColors.Plum);

                        case "powderblue": return(SKColors.PowderBlue);

                        case "purple": return(SKColors.Purple);

                        case "red": return(SKColors.Red);

                        case "rosybrown": return(SKColors.RosyBrown);

                        case "royalblue": return(SKColors.RoyalBlue);

                        case "saddlebrown": return(SKColors.SaddleBrown);

                        case "salmon": return(SKColors.Salmon);

                        case "sandybrown": return(SKColors.SandyBrown);

                        case "seagreen": return(SKColors.SeaGreen);

                        case "seashell": return(SKColors.SeaShell);

                        case "sienna": return(SKColors.Sienna);

                        case "silver": return(SKColors.Silver);

                        case "skyblue": return(SKColors.SkyBlue);

                        case "slateblue": return(SKColors.SlateBlue);

                        case "slategray": return(SKColors.SlateGray);

                        case "snow": return(SKColors.Snow);

                        case "springgreen": return(SKColors.SpringGreen);

                        case "steelblue": return(SKColors.SteelBlue);

                        case "tan": return(SKColors.Tan);

                        case "teal": return(SKColors.Teal);

                        case "thistle": return(SKColors.Thistle);

                        case "tomato": return(SKColors.Tomato);

                        case "transparent": return(SKColors.Transparent);

                        case "turquoise": return(SKColors.Turquoise);

                        case "violet": return(SKColors.Violet);

                        case "wheat": return(SKColors.Wheat);

                        case "white": return(SKColors.White);

                        case "whitesmoke": return(SKColors.WhiteSmoke);

                        case "yellow": return(SKColors.Yellow);

                        case "yellowgreen": return(SKColors.YellowGreen);
                        }
                        var field = typeof(SKColors).GetFields().FirstOrDefault(fi => fi.IsStatic && string.Equals(fi.Name, color, StringComparison.OrdinalIgnoreCase));
                        if (field != null)
                        {
                            return((SKColor)field.GetValue(null));
                        }
                        var property = typeof(SKColors).GetProperties().FirstOrDefault(pi => string.Equals(pi.Name, color, StringComparison.OrdinalIgnoreCase) && pi.CanRead && pi.GetMethod.IsStatic);
                        if (property != null)
                        {
                            return((SKColor)property.GetValue(null, null));
                        }
                    }
                }
            }
            throw new InvalidOperationException(string.Format("Cannot convert \"{0}\" into {1}", new object[]
            {
                value,
                typeof(SKColor)
            }));
        }
Beispiel #25
0
        public override void Render(IStateOwner pOwner, SKCanvas pRenderTarget, ViewScoreDetailsState Source, GameStateSkiaDrawParameters Element)
        {
            //TODO: finish this!
            var g      = pRenderTarget;
            var Bounds = Element.Bounds;

            //Draw the background first.
            RenderingProvider.Static.DrawElement(pOwner, pRenderTarget, Source.BG, new SkiaBackgroundDrawData(Bounds));

            DrawTextInformationSkia skdraw = new DrawTextInformationSkia()
            {
                ForegroundPaint = new SKPaint()
            };

            float StartY   = (Bounds.Height * 0.175f);
            var   CurrentY = StartY;
            float MiddleX  = Bounds.Width / 2;

            float   TextSize      = Bounds.Height / 30f;
            var     ScoreFont     = TetrisGame.RetroFontSK; //point size 24.
            SKPaint MainScoreFont = new SKPaint()
            {
                Typeface = ScoreFont, TextSize = (float)(24 * pOwner.ScaleFactor), Color = SKColors.Black
            };
            SKPaint ShadowScoreFont = new SKPaint()
            {
                Typeface = ScoreFont, TextSize = (float)(24 * pOwner.ScaleFactor), Color = SKColors.White
            };
            SKPaint ListingFont = new SKPaint()
            {
                Typeface = ScoreFont, TextSize = (float)(18 * pOwner.ScaleFactor), Color = SKColors.Black
            };
            float   PercentThroughSecond = (float)DateTime.Now.Millisecond / 1000f;
            SKPaint ListingFontRainbow   = new SKPaint()
            {
                Typeface = ScoreFont, TextSize = (float)(18 * pOwner.ScaleFactor), Color = SKColor.FromHsl(PercentThroughSecond * 240, 240, 120)
            };
            SKPaint ListingFontShadow = new SKPaint()
            {
                Typeface = ScoreFont, TextSize = (float)(18 * pOwner.ScaleFactor), Color = SKColors.White
            };
            SKPaint ListingFontArrow = new SKPaint()
            {
                Typeface = TetrisGame.ArialFontSK, TextSize = (float)(18 * pOwner.ScaleFactor), Color = SKColor.FromHsl(PercentThroughSecond * 240, 240, 120)
            };
            SKPaint ListingFontArrowShadow = new SKPaint()
            {
                Typeface = TetrisGame.ArialFontSK, TextSize = (float)(18 * pOwner.ScaleFactor), Color = SKColors.White
            };
            SKRect resultitem = new SKRect();
            float  LineHeight = MainScoreFont.MeasureText("#", ref resultitem);
            var    useShader  = SKShader.CreateLinearGradient(new SKPoint(0, 0), new SKPoint(0, Bounds.Height), new SKColor[] { SKColors.Red, SKColors.Orange, SKColors.Yellow, SKColors.Green, SKColors.Blue, SKColors.Indigo, SKColors.Violet }, null, SKShaderTileMode.Mirror);

            SKPaint LinePaint = new SKPaint()
            {
                BlendMode = SKBlendMode.ColorBurn, StrokeWidth = 24, Shader = useShader
            };

            g.DrawRect(new SKRect(0, 0, Bounds.Width, Bounds.Height), LinePaint);
            //g.DrawRect(new SKRect((int)(Bounds.Width * (1 / 7)), CurrentY, (float)(Bounds.Width - (Bounds.Width * (1 / 7))), (float)(CurrentY + (LineHeight * 2.5) + (LineHeight * 3) * 12)),LinePaint);



            if (Source.IncrementedDrawState >= 0)
            {
                //draw "SCORE DETAILS"
                String sHeaderText  = "SCORE DETAILS";
                SKRect MeasuredRect = new SKRect();
                MainScoreFont.MeasureText(sHeaderText, ref MeasuredRect);
                SKPoint DrawPosition = new SKPoint(MiddleX - (MeasuredRect.Width / 2), StartY);
                g.DrawText(sHeaderText, new SKPoint(DrawPosition.X + 2, DrawPosition.Y + 2), ShadowScoreFont);
                g.DrawText(sHeaderText, DrawPosition, MainScoreFont);
                CurrentY = StartY + MeasuredRect.Height + 10;
            }

            if (Source.IncrementedDrawState >= 1)
            {
                //maybe a line under the header.
            }

            if (Source.IncrementedDrawState >= 2)
            {
                switch (Source.CurrentView)
                {
                case ViewScoreDetailsState.ViewScoreDetailsType.Details_Tetrominoes:
                    DrawTetronimoDetails(Source, g, Bounds, CurrentY);
                    break;

                case ViewScoreDetailsState.ViewScoreDetailsType.Details_LevelTimes:
                    DrawLevelTimesDetails(Source, g, Bounds, CurrentY);
                    break;
                }
                //draw the high score listing entries.
                //iterate from 2 to drawstate and draw the high score at position drawstate-2.

                /*for (int scoreiterate = 2; scoreiterate < Source.IncrementedDrawState; scoreiterate++)
                 * {
                 *  int CurrentScoreIndex = scoreiterate - 2;
                 *  int CurrentScorePosition = CurrentScoreIndex + 1;
                 *  double useYPosition = StartY + (LineHeight * 2.5) + (LineHeight * 3) * CurrentScoreIndex;
                 *  double useXPosition = Bounds.Width * 0.19d;
                 *  String sUseName = "N/A";
                 *  int sUseScore = 0;
                 *  IHighScoreEntry currentScore = Source.hs.Count > CurrentScoreIndex ? Source.hs[CurrentScoreIndex] : null;
                 *  if (currentScore != null)
                 *  {
                 *      sUseName = currentScore.Name;
                 *      sUseScore = currentScore.Score;
                 *  }
                 *  SKRect MeasureName = new SKRect(), MeasureScore = new SKRect();
                 *  ListingFont.MeasureText(sUseName, ref MeasureName);
                 *  ListingFont.MeasureText(sUseScore.ToString(), ref MeasureScore);
                 *  float PosXPosition = Bounds.Width * 0.1f;
                 *  float NameXPosition = Bounds.Width * 0.20f;
                 *  float ScoreXPositionRight = Bounds.Width * (1 - 0.10f);
                 *  var useForegroundPaint = Source.HighlightedScorePositions.Contains(CurrentScorePosition) ? ListingFontRainbow : ListingFont;
                 *
                 *  //draw position
                 *  g.DrawText(CurrentScorePosition.ToString() + ".", new SKPoint(PosXPosition + 2, (float)useYPosition + 2), ListingFontShadow);
                 *  g.DrawText(CurrentScorePosition.ToString() + ".", new SKPoint(PosXPosition, (float)useYPosition), useForegroundPaint);
                 *  //draw high score name
                 *  g.DrawText(sUseName, new SKPoint(PosXPosition + 2 + Math.Abs(resultitem.Height) * 2.25f, (float)useYPosition + 2), ListingFontShadow);
                 *  g.DrawText(sUseName, new SKPoint(PosXPosition + Math.Abs(resultitem.Height) * 2.25f, (float)useYPosition), useForegroundPaint);
                 *
                 *  //draw the high score
                 *  float ScoreXPosition = ScoreXPositionRight - MeasureScore.Width;
                 *
                 *  g.DrawText(sUseScore.ToString(), new SKPoint(ScoreXPosition + 2, (float)useYPosition + 2), ListingFontShadow);
                 *  g.DrawText(sUseScore.ToString(), new SKPoint(ScoreXPosition, (float)useYPosition), useForegroundPaint);
                 *  useForegroundPaint.StrokeWidth = 6;
                 *
                 *  g.DrawLine(new SKPoint(NameXPosition + MeasureName.Width + 15, (float)useYPosition + LineHeight / 2), new SKPoint(ScoreXPosition - 15, (float)useYPosition + LineHeight / 2), useForegroundPaint);
                 *
                 *  if (Source.SelectedScorePosition == CurrentScoreIndex)
                 *  {
                 *      //draw selection indicator if needed
                 *      SKRect MeasureArrow = new SKRect();
                 *      useForegroundPaint.MeasureText(PointerText, ref MeasureArrow);
                 *      float ArrowX = PosXPosition - MeasureArrow.Width - 5;
                 *      float ArrowY = (float)useYPosition;
                 *      g.DrawText(PointerText, new SKPoint(ArrowX + 2, ArrowY + 2), ListingFontArrowShadow);
                 *      g.DrawText(PointerText, new SKPoint(ArrowX, ArrowY), ListingFontArrow);
                 *  }
                 * }*/
            }

            /*
             *
             * Font HeaderFont = TetrisGame.GetRetroFont(24, pOwner.ScaleFactor);
             * Font PlacementFont = TetrisGame.GetRetroFont(10, pOwner.ScaleFactor);
             * Font DetailFont = TetrisGame.GetRetroFont(8, pOwner.ScaleFactor);
             *
             *
             * //One thing we draw in every case is the "--SCORE DETAILS--" header text. this is positioned at 5% from the top, centered in the middle of our bounds.
             * float Millipercent = (float)DateTime.Now.Ticks / 5000f; //(float)DateTime.Now.Millisecond / 1000;
             *
             * var MeasuredHeader = g.MeasureString(Source._DetailHeader, HeaderFont);
             * int RotateAmount = (int)(Millipercent * 240);
             * Color UseColor1 = HSLColor.RotateHue(Color.Red, RotateAmount);
             * Color UseColor2 = HSLColor.RotateHue(Color.LightPink, RotateAmount);
             * PointF ScorePosition = new PointF((Bounds.Width / 2) - (MeasuredHeader.Width / 2), Bounds.Height * 0.05f);
             * using (LinearGradientBrush lgb = new LinearGradientBrush(new Rectangle(0, 0, (int)MeasuredHeader.Width, (int)MeasuredHeader.Height), UseColor1, UseColor2, LinearGradientMode.Vertical))
             * {
             *  using (GraphicsPath gp = new GraphicsPath())
             *  {
             *      gp.AddString(Source._DetailHeader, HeaderFont, new Point((int)ScorePosition.X, (int)ScorePosition.Y), StringFormat.GenericDefault);
             *      g.FillPath(lgb, gp);
             *      g.DrawPath(Pens.White, gp);
             *  }
             * }
             *
             * //we also show Xth Place - <NAME> centered below the header using the placementfont.
             * String sPlacement = TetrisGame.FancyNumber(Source._Position) + " - " + Source.ShowEntry.Name + " - " + Source.ShowEntry.Score.ToString();
             *
             * var measureit = g.MeasureString(sPlacement, PlacementFont);
             *
             * PointF DrawPlacement = new PointF(Bounds.Width / 2 - measureit.Width / 2, (float)(ScorePosition.Y + MeasuredHeader.Height * 1.1f));
             *
             * g.DrawString(sPlacement, PlacementFont, Brushes.Black, DrawPlacement.X + 3, DrawPlacement.Y + 3);
             * g.DrawString(sPlacement, PlacementFont, Brushes.White, DrawPlacement.X, DrawPlacement.Y);
             *
             * g.DrawLine(Separator, (float)(Bounds.Width * 0.05f), (float)(DrawPlacement.Y + measureit.Height + 5), (float)(Bounds.Width * 0.95), (float)(DrawPlacement.Y + measureit.Height + 5));
             *
             *
             * switch (Source.CurrentView)
             * {
             *  case ViewScoreDetailsState.ViewScoreDetailsType.Details_Tetrominoes:
             *      DrawTetronimoDetails(Source, g, Bounds);
             *      break;
             *  case ViewScoreDetailsState.ViewScoreDetailsType.Details_LevelTimes:
             *      DrawLevelTimesDetails(Source, g, Bounds);
             *      break;
             * }
             */
        }
Beispiel #26
0
        public override void Render(IStateOwner pOwner, SKCanvas pRenderTarget, ShowHighScoresState Source, GameStateSkiaDrawParameters Element)
        {
            if (Source.BG == null)
            {
                StandardImageBackgroundSkia sk = StandardImageBackgroundSkia.GetMenuBackgroundDrawer();
                sk.Data.Movement = new SKPoint(3, 3);
                Source.BG        = sk;
            }
            var Bounds = Element.Bounds;
            var g      = pRenderTarget;

            float StartY   = (Bounds.Height * 0.175f);
            var   CurrentY = StartY;
            float MiddleX  = Bounds.Width / 2;

            DrawBackground(Source, pOwner, g, Bounds);
            float   TextSize      = Bounds.Height / 30f;
            var     ScoreFont     = TetrisGame.RetroFontSK; //point size 24.
            SKPaint MainScoreFont = new SKPaint()
            {
                Typeface = ScoreFont, TextSize = (float)(24 * pOwner.ScaleFactor), Color = SKColors.Black
            };
            SKPaint ShadowScoreFont = new SKPaint()
            {
                Typeface = ScoreFont, TextSize = (float)(24 * pOwner.ScaleFactor), Color = SKColors.White
            };
            SKPaint ListingFont = new SKPaint()
            {
                Typeface = ScoreFont, TextSize = (float)(18 * pOwner.ScaleFactor), Color = SKColors.Black
            };
            float   PercentThroughSecond = (float)DateTime.Now.Millisecond / 1000f;
            SKPaint ListingFontRainbow   = new SKPaint()
            {
                Typeface = ScoreFont, TextSize = (float)(18 * pOwner.ScaleFactor), Color = SKColor.FromHsl(PercentThroughSecond * 240, 240, 120)
            };
            SKPaint ListingFontShadow = new SKPaint()
            {
                Typeface = ScoreFont, TextSize = (float)(18 * pOwner.ScaleFactor), Color = SKColors.White
            };
            SKPaint ListingFontArrow = new SKPaint()
            {
                Typeface = TetrisGame.ArialFontSK, TextSize = (float)(18 * pOwner.ScaleFactor), Color = SKColor.FromHsl(PercentThroughSecond * 240, 240, 120)
            };
            SKPaint ListingFontArrowShadow = new SKPaint()
            {
                Typeface = TetrisGame.ArialFontSK, TextSize = (float)(18 * pOwner.ScaleFactor), Color = SKColors.White
            };
            SKRect resultitem = new SKRect();
            float  LineHeight = MainScoreFont.MeasureText("#", ref resultitem);
            var    useShader  = SKShader.CreateLinearGradient(new SKPoint(0, 0), new SKPoint(0, Bounds.Height), new SKColor[] { SKColors.Red, SKColors.Orange, SKColors.Yellow, SKColors.Green, SKColors.Blue, SKColors.Indigo, SKColors.Violet }, null, SKShaderTileMode.Mirror);

            SKPaint LinePaint = new SKPaint()
            {
                BlendMode = SKBlendMode.ColorBurn, StrokeWidth = 24, Shader = useShader
            };

            g.DrawRect(new SKRect(0, 0, Bounds.Width, Bounds.Height), LinePaint);
            //g.DrawRect(new SKRect((int)(Bounds.Width * (1 / 7)), CurrentY, (float)(Bounds.Width - (Bounds.Width * (1 / 7))), (float)(CurrentY + (LineHeight * 2.5) + (LineHeight * 3) * 12)),LinePaint);



            if (Source.IncrementedDrawState >= 0)
            {
                //draw "HIGH SCORES" header text.
                SKRect MeasuredRect = new SKRect();
                MainScoreFont.MeasureText(Source.HeaderText, ref MeasuredRect);
                SKPoint DrawPosition = new SKPoint(MiddleX - (MeasuredRect.Width / 2), StartY);
                g.DrawText(Source.HeaderText, new SKPoint(DrawPosition.X + 2, DrawPosition.Y + 2), ShadowScoreFont);
                g.DrawText(Source.HeaderText, DrawPosition, MainScoreFont);
                CurrentY = StartY + MeasuredRect.Height + 10;
            }

            if (Source.IncrementedDrawState >= 1)
            {
                //maybe a line under the header.
            }

            if (Source.IncrementedDrawState >= 2)
            {
                //draw the high score listing entries.
                //iterate from 2 to drawstate and draw the high score at position drawstate-2.
                for (int scoreiterate = 2; scoreiterate < Source.IncrementedDrawState; scoreiterate++)
                {
                    int             CurrentScoreIndex    = scoreiterate - 2;
                    int             CurrentScorePosition = CurrentScoreIndex + 1;
                    double          useYPosition         = StartY + (LineHeight * 2.5) + (LineHeight * 3) * CurrentScoreIndex;
                    double          useXPosition         = Bounds.Width * 0.19d;
                    String          sUseName             = "N/A";
                    int             sUseScore            = 0;
                    IHighScoreEntry currentScore         = Source.hs.Count > CurrentScoreIndex ? Source.hs[CurrentScoreIndex] : null;
                    if (currentScore != null)
                    {
                        sUseName  = currentScore.Name;
                        sUseScore = currentScore.Score;
                    }
                    SKRect MeasureName = new SKRect(), MeasureScore = new SKRect();
                    ListingFont.MeasureText(sUseName, ref MeasureName);
                    ListingFont.MeasureText(sUseScore.ToString(), ref MeasureScore);
                    float PosXPosition        = Bounds.Width * 0.1f;
                    float NameXPosition       = Bounds.Width * 0.20f;
                    float ScoreXPositionRight = Bounds.Width * (1 - 0.10f);
                    var   useForegroundPaint  = Source.HighlightedScorePositions.Contains(CurrentScorePosition) ? ListingFontRainbow : ListingFont;

                    //draw position
                    g.DrawText(CurrentScorePosition.ToString() + ".", new SKPoint(PosXPosition + 2, (float)useYPosition + 2), ListingFontShadow);
                    g.DrawText(CurrentScorePosition.ToString() + ".", new SKPoint(PosXPosition, (float)useYPosition), useForegroundPaint);
                    //draw high score name
                    g.DrawText(sUseName, new SKPoint(PosXPosition + 2 + Math.Abs(resultitem.Height) * 2.25f, (float)useYPosition + 2), ListingFontShadow);
                    g.DrawText(sUseName, new SKPoint(PosXPosition + Math.Abs(resultitem.Height) * 2.25f, (float)useYPosition), useForegroundPaint);

                    //draw the high score
                    float ScoreXPosition = ScoreXPositionRight - MeasureScore.Width;

                    g.DrawText(sUseScore.ToString(), new SKPoint(ScoreXPosition + 2, (float)useYPosition + 2), ListingFontShadow);
                    g.DrawText(sUseScore.ToString(), new SKPoint(ScoreXPosition, (float)useYPosition), useForegroundPaint);
                    useForegroundPaint.StrokeWidth = 6;

                    g.DrawLine(new SKPoint(NameXPosition + MeasureName.Width + 15, (float)useYPosition + LineHeight / 2), new SKPoint(ScoreXPosition - 15, (float)useYPosition + LineHeight / 2), useForegroundPaint);

                    if (Source.SelectedScorePosition == CurrentScoreIndex)
                    {
                        //draw selection indicator if needed
                        SKRect MeasureArrow = new SKRect();
                        useForegroundPaint.MeasureText(PointerText, ref MeasureArrow);
                        float ArrowX = PosXPosition - MeasureArrow.Width - 5;
                        float ArrowY = (float)useYPosition;
                        g.DrawText(PointerText, new SKPoint(ArrowX + 2, ArrowY + 2), ListingFontArrowShadow);
                        g.DrawText(PointerText, new SKPoint(ArrowX, ArrowY), ListingFontArrow);
                    }
                }
            }
        }
        public StaticInfoDetails()
        {
            List <CoffeeType> watertypes    = Logic.GetWaterTypes();
            List <CoffeeType> mattressTypes = Logic.GetMattressTypes();
            List <CoffeeType> tableTypes    = Logic.GetTableTypes();
            List <CoffeeType> chairTypes    = Logic.GetChairTypes();
            List <CoffeeType> coffeeTypes   = Logic.GetCoffeeTypes();
            List <HowOften>   howOftens     = Logic.GetHowOftens();

            ComfortProfile comfortProfile = Logic.GetComfortProfile();

            InitializeComponent();

            Body.Children.Add(new Label()
            {
                Text              = "It's your comfort profile. You can share it by link using button in the bottom of the page.",
                TextColor         = Color.Black,
                FontFamily        = "Raleway-Medium.ttf#Raleway",
                FontSize          = 19,
                VerticalOptions   = LayoutOptions.Start,
                HorizontalOptions = LayoutOptions.StartAndExpand,
                Margin            = new Thickness(20, 18, 20, 0)
            });

            Body.Children.Add(new Label()
            {
                Text       = "Personal: ",
                TextColor  = Color.Black,
                FontFamily = "Raleway-Bold.ttf#Raleway",
                FontSize   = 18,
                Margin     = new Thickness(20, 5, 20, 0)
            });

            var shoeSizeImage = new Image()
            {
                Source = "shoe.png",
                Margin = new Thickness(20, 14, 5, 0)
            };

            var shoeSizeLabel = new Label()
            {
                Text       = "Shoe size: " + comfortProfile.shoeSize,
                TextColor  = Color.Black,
                FontFamily = "Raleway-Medium.ttf#Raleway",
                FontSize   = 17,
                Margin     = new Thickness(5, 23, 5, 0)
            };

            Body.Children.Add(new StackLayout()
            {
                Orientation       = StackOrientation.Horizontal,
                VerticalOptions   = LayoutOptions.Center,
                HorizontalOptions = LayoutOptions.StartAndExpand,
                Children          = { shoeSizeImage, shoeSizeLabel }
            });

            var clothesSizeImage = new Image()
            {
                Source = "clothes.png",
                Margin = new Thickness(20, 14, 5, 0)
            };

            var clothesSizeLabel = new Label()
            {
                Text       = "Clothing size: " + comfortProfile.clothingSize,
                TextColor  = Color.Black,
                FontFamily = "Raleway-Medium.ttf#Raleway",
                FontSize   = 17,
                Margin     = new Thickness(5, 23, 5, 0)
            };

            Body.Children.Add(new StackLayout()
            {
                Orientation       = StackOrientation.Horizontal,
                VerticalOptions   = LayoutOptions.Center,
                HorizontalOptions = LayoutOptions.StartAndExpand,
                Children          = { clothesSizeImage, clothesSizeLabel }
            });

            var allergensImage = new Image()
            {
                Source = "allergens.png",
                Margin = new Thickness(20, 14, 5, 0)
            };

            var allergensLabel = new Label()
            {
                Text       = "Allergens: " + comfortProfile.allergens,
                TextColor  = Color.Black,
                FontFamily = "Raleway-Medium.ttf#Raleway",
                FontSize   = 17,
                Margin     = new Thickness(5, 23, 5, 0)
            };

            Body.Children.Add(new StackLayout()
            {
                Orientation       = StackOrientation.Horizontal,
                VerticalOptions   = LayoutOptions.Center,
                HorizontalOptions = LayoutOptions.StartAndExpand,
                Children          = { allergensImage, allergensLabel }
            });

            var musicalPreferencesImage = new Image()
            {
                Source = "music.png",
                Margin = new Thickness(20, 14, 5, 0)
            };

            var musicalPreferencesLabel = new Label()
            {
                Text       = comfortProfile.musicalPreferences,
                TextColor  = Color.Black,
                FontFamily = "Raleway-Medium.ttf#Raleway",
                FontSize   = 17,
                Margin     = new Thickness(5, 23, 5, 0)
            };

            Body.Children.Add(new StackLayout()
            {
                Orientation       = StackOrientation.Horizontal,
                VerticalOptions   = LayoutOptions.Center,
                HorizontalOptions = LayoutOptions.StartAndExpand,
                Children          = { musicalPreferencesImage, musicalPreferencesLabel }
            });

            var fruitPreferencesImage = new Image()
            {
                Source = "fruit.png",
                Margin = new Thickness(20, 14, 5, 0)
            };

            var fruitPreferencesLabel = new Label()
            {
                Text       = "Fruits preferences: " + comfortProfile.fruitPreferences,
                TextColor  = Color.Black,
                FontFamily = "Raleway-Medium.ttf#Raleway",
                FontSize   = 17,
                Margin     = new Thickness(5, 23, 5, 0)
            };

            Body.Children.Add(new StackLayout()
            {
                Orientation       = StackOrientation.Horizontal,
                VerticalOptions   = LayoutOptions.Center,
                HorizontalOptions = LayoutOptions.StartAndExpand,
                Children          = { fruitPreferencesImage, fruitPreferencesLabel }
            });

            Body.Children.Add(new Label()
            {
                Text       = "House: ",
                TextColor  = Color.Black,
                FontFamily = "Raleway-Bold.ttf#Raleway",
                FontSize   = 18,
                Margin     = new Thickness(20, 15, 20, 0)
            });

            var chairTypeImage = new Image()
            {
                Source = "chair.png",
                Margin = new Thickness(20, 14, 5, 0)
            };

            var chairTypeLable = new Label()
            {
                Text       = "Preferable chair type: " + chairTypes.FirstOrDefault(chairType => chairType.Id == comfortProfile.chairTypeId.ToString()).Name,
                TextColor  = Color.Black,
                FontFamily = "Raleway-Medium.ttf#Raleway",
                FontSize   = 17,
                Margin     = new Thickness(5, 21, 5, 0)
            };

            Body.Children.Add(new StackLayout()
            {
                Orientation       = StackOrientation.Horizontal,
                VerticalOptions   = LayoutOptions.Center,
                HorizontalOptions = LayoutOptions.StartAndExpand,
                Children          = { chairTypeImage, chairTypeLable }
            });

            var tableTypeImage = new Image()
            {
                Source = "table.png",
                Margin = new Thickness(20, 14, 5, 0)
            };

            var tableTypeLabel = new Label()
            {
                Text       = "Preferable table type: " + tableTypes.FirstOrDefault(tableType => tableType.Id == comfortProfile.tableTypeId.ToString()).Name,
                TextColor  = Color.Black,
                FontFamily = "Raleway-Medium.ttf#Raleway",
                FontSize   = 17,
                Margin     = new Thickness(5, 21, 5, 0)
            };

            Body.Children.Add(new StackLayout()
            {
                Orientation       = StackOrientation.Horizontal,
                VerticalOptions   = LayoutOptions.Center,
                HorizontalOptions = LayoutOptions.StartAndExpand,
                Children          = { tableTypeImage, tableTypeLabel }
            });

            var mattressTypeImage = new Image()
            {
                Source = "mattress.png",
                Margin = new Thickness(20, 14, 5, 0)
            };

            var mattressTypeLabel = new Label()
            {
                Text       = "Preferable mattress type: " + mattressTypes.FirstOrDefault(mattressType => mattressType.Id == comfortProfile.mattressTypeId.ToString()).Name,
                TextColor  = Color.Black,
                FontFamily = "Raleway-Medium.ttf#Raleway",
                FontSize   = 17,
                Margin     = new Thickness(5, 21, 5, 0)
            };

            Body.Children.Add(new StackLayout()
            {
                Orientation       = StackOrientation.Horizontal,
                VerticalOptions   = LayoutOptions.Center,
                HorizontalOptions = LayoutOptions.StartAndExpand,
                Children          = { mattressTypeImage, mattressTypeLabel }
            });

            Body.Children.Add(new Label()
            {
                Text       = "Rooms: ",
                TextColor  = Color.Black,
                FontFamily = "Raleway-Medium.ttf#Raleway",
                FontSize   = 18,
                Margin     = new Thickness(20, 15, 20, 0)
            });

            foreach (var room in comfortProfile.preferableRoomsIndicators)
            {
                Random rand = new Random();

                var frame = new Frame()
                {
                    BorderColor   = Color.White,
                    CornerRadius  = 2,
                    HasShadow     = true,
                    HeightRequest = 160
                };

                var image = new Image()
                {
                    Source = "test.jpg",
                    Aspect = Aspect.Fill
                };
                var grid     = new Grid();
                var roomCard = new StackLayout();

                roomCard.Children.Add(new Label()
                {
                    Text           = room.name,
                    FontAttributes = FontAttributes.Bold,
                    FontSize       = 29,
                    FontFamily     = "Raleway-Bold.ttf#Raleway",
                    TextColor      = Color.White,
                    Margin         = new Thickness(20, 10, 0, 2)
                });

                if (room.preferableTemperature == null)
                {
                    room.preferableTemperature = rand.Next(20, 40);
                }

                roomCard.Children.Add(new Label()
                {
                    Text       = "Preferable Temperature: " + room.preferableTemperature + "°C",
                    FontSize   = 18,
                    FontFamily = "Raleway-Medium.ttf#Raleway",
                    TextColor  = Color.White,
                    Margin     = new Thickness(20, 2)
                });

                if (room.preferableAirHumidity == null)
                {
                    room.preferableAirHumidity = rand.Next(20, 60);
                }

                roomCard.Children.Add(new Label()
                {
                    Text       = "Preferable Air Humidity: " + room.preferableAirHumidity + "%",
                    FontSize   = 18,
                    FontFamily = "Raleway-Medium.ttf#Raleway",
                    TextColor  = Color.White,
                    Margin     = new Thickness(20, 2)
                });

                if (room.preferableLightIntencity == null)
                {
                    room.preferableLightIntencity = rand.Next(30, 100);
                }

                roomCard.Children.Add(new Label()
                {
                    Text       = "Preferable Light Intensity: " + room.preferableLightIntencity + "%",
                    FontSize   = 18,
                    FontFamily = "Raleway-Medium.ttf#Raleway",
                    TextColor  = Color.White,
                    Margin     = new Thickness(20, 2)
                });

                grid.Children.Add(image);
                grid.Children.Add(roomCard);
                frame.Content = grid;
                Body.Children.Add(frame);
            }

            Body.Children.Add(new Label()
            {
                Text       = "Other: ",
                TextColor  = Color.Black,
                FontFamily = "Raleway-Bold.ttf#Raleway",
                FontSize   = 18,
                Margin     = new Thickness(20, 15, 20, 0)
            });

            var teapotImage = new Image()
            {
                Source = "temperature.png",
                Margin = new Thickness(20, 14, 5, 0)
            };

            var teapotLabel = new Label()
            {
                Text       = "Preferable water in teapot temperature: " + comfortProfile.comfortTeapotTemperature + "°C",
                TextColor  = Color.Black,
                FontFamily = "Raleway-Medium.ttf#Raleway",
                FontSize   = 17,
                Margin     = new Thickness(5, 21, 5, 0)
            };

            Body.Children.Add(new StackLayout()
            {
                Orientation       = StackOrientation.Horizontal,
                VerticalOptions   = LayoutOptions.Center,
                HorizontalOptions = LayoutOptions.StartAndExpand,
                Children          = { teapotImage, teapotLabel }
            });

            var teaImage = new Image()
            {
                Source = "tea.png",
                Margin = new Thickness(20, 14, 5, 0)
            };

            var teaLabel = new Label()
            {
                Text       = "Favourite kinds of tea" + comfortProfile.kindOfTea,
                TextColor  = Color.Black,
                FontFamily = "Raleway-Medium.ttf#Raleway",
                FontSize   = 17,
                Margin     = new Thickness(5, 21, 5, 0)
            };

            Body.Children.Add(new StackLayout()
            {
                Orientation       = StackOrientation.Horizontal,
                VerticalOptions   = LayoutOptions.Center,
                HorizontalOptions = LayoutOptions.StartAndExpand,
                Children          = { teaImage, teaLabel }
            });

            var teaTimesImage = new Image()
            {
                Source = "time.png",
                Margin = new Thickness(20, 14, 5, 0)
            };

            var teaTimesLabel = new Label()
            {
                Text       = "Times when water should be boiled up to specific temperature:",
                TextColor  = Color.Black,
                FontFamily = "Raleway-Medium.ttf#Raleway",
                FontSize   = 17,
                Margin     = new Thickness(5, 21, 5, 0)
            };

            Body.Children.Add(new StackLayout()
            {
                Orientation       = StackOrientation.Horizontal,
                VerticalOptions   = LayoutOptions.Center,
                HorizontalOptions = LayoutOptions.StartAndExpand,
                Children          = { teaTimesImage, teaTimesLabel }
            });

            if (comfortProfile.preferableTeaTimes != null)
            {
                foreach (var ptt in comfortProfile.preferableTeaTimes)
                {
                    Body.Children.Add(new Label()
                    {
                        Text       = "Boil water to " + ptt.temperature + "°C" + howOftens.FirstOrDefault(ho => ho.Id == ptt.howOftenId).Explanation + " at " + ptt.date.ToShortTimeString(),
                        TextColor  = Color.Black,
                        FontFamily = "Raleway-Medium.ttf#Raleway",
                        FontSize   = 17,
                        Margin     = new Thickness(67, 8, 5, 0)
                    });
                }
            }
            else
            {
                Body.Children.Add(new Label()
                {
                    Text       = "Unfoturnately, we don't have needed amount of information to fill this section.",
                    TextColor  = Color.Black,
                    FontFamily = "Raleway-Medium.ttf#Raleway",
                    FontSize   = 17,
                    Margin     = new Thickness(67, 8, 5, 0)
                });
            }

            Body.Children.Add(new Label()
            {
                Text       = "Favourite coffee types: ",
                TextColor  = Color.Black,
                FontFamily = "Raleway-Medium.ttf#Raleway",
                FontSize   = 17,
                Margin     = new Thickness(20, 14, 5, 0)
            });

            List <Microcharts.Entry> entries = new List <Microcharts.Entry>();
            Random r = new Random();

            foreach (var fct in comfortProfile.favoriteCoffeeTypes)
            {
                var value = r.Next(20, 60);

                entries.Add(new Microcharts.Entry(value)
                {
                    Color      = SKColor.FromHsl(r.Next(0, 265), r.Next(0, 265), r.Next(0, 265)),
                    Label      = coffeeTypes.First(ct => ct.Id == fct.id).Name,
                    ValueLabel = value.ToString() + "%"
                });
            }

            FavouriteCoffeeChart.Chart = new DonutChart()
            {
                Entries = entries
            };

            var coffeeTimesImage = new Image()
            {
                Source = "time.png",
                Margin = new Thickness(20, 14, 5, 0)
            };

            var coffeeTimesLabel = new Label()
            {
                Text       = "When coffee should be done: ",
                TextColor  = Color.Black,
                FontFamily = "Raleway-Medium.ttf#Raleway",
                FontSize   = 17,
                Margin     = new Thickness(5, 21, 5, 0)
            };

            ContinueBody.Children.Add(new StackLayout()
            {
                Orientation       = StackOrientation.Horizontal,
                VerticalOptions   = LayoutOptions.Center,
                HorizontalOptions = LayoutOptions.StartAndExpand,
                Children          = { coffeeTimesImage, coffeeTimesLabel }
            });

            if (comfortProfile.preferableCoffeeTimes != null)
            {
                foreach (var ptt in comfortProfile.preferableCoffeeTimes)
                {
                    ContinueBody.Children.Add(new Label()
                    {
                        Text       = "Make " + coffeeTypes.FirstOrDefault(ct => ct.Id == ptt.coffeeTypeId).Name + " " + howOftens.FirstOrDefault(ho => ho.Id == ptt.howOftenId).Explanation + " at " + ptt.date.ToShortTimeString(),
                        TextColor  = Color.Black,
                        FontFamily = "Raleway-Medium.ttf#Raleway",
                        FontSize   = 17,
                        Margin     = new Thickness(67, 8, 5, 0)
                    });
                }
            }
            else
            {
                ContinueBody.Children.Add(new Label()
                {
                    Text       = "Unfoturnately, we don't have needed amount of information to fill these sectoin.",
                    TextColor  = Color.Black,
                    FontFamily = "Raleway-Medium.ttf#Raleway",
                    FontSize   = 17,
                    Margin     = new Thickness(67, 8, 5, 0)
                });
            }
        }
Beispiel #28
0
        public general()
        {
            InitializeComponent();

            // Scale chart to overlay the fourier graph
            List <Entry> scaleEntries = new List <Entry>();

            for (int j = 0; j < 125; j++)
            {
                if (j % 25 == 0 && j > 0)
                {
                    scaleEntries.Add(new Entry((int)(j / 2.5))
                    {
                        ValueLabel = ((int)(j / 2.5)).ToString(), Color = SKColor.FromHsl(1, 100, 100, 255)
                    });
                }
                else
                {
                    scaleEntries.Add(new Entry((int)(j / 2.5)));
                }
            }
            var scaleChart = new LineChart()
            {
                Entries         = scaleEntries,
                LineMode        = LineMode.None,
                PointMode       = PointMode.None,
                LabelTextSize   = 50,
                PointSize       = 0,
                BackgroundColor = SKColor.FromHsl(243, 100, 50, 0)
            };

            this.fourierScaleChart.Chart = scaleChart;

            FourierTransformer ft            = new FourierTransformer(250);
            List <Complex>     headBandInput = new List <Complex>();
            //double Fs = 100;

            // Headband entries
            List <Entry> entries      = new List <Entry>();
            List <Entry> chartEntries = new List <Entry>();
            // The list that will contain all the fourier data
            List <Entry> fourierTransform = new List <Entry>();
            List <Entry> barEntries       = new List <Entry>();

            // Headset entries
            List <Entry> temperatureEntries = new List <Entry>();
            List <Entry> accelXEntries      = new List <Entry>();
            List <Entry> accelYEntries      = new List <Entry>();
            List <Entry> accelZEntries      = new List <Entry>();
            List <Entry> gyXEntries         = new List <Entry>();
            List <Entry> gyYEntries         = new List <Entry>();
            List <Entry> gyZEntries         = new List <Entry>();
            List <Entry> presEntries        = new List <Entry>();

            List <Entry> speedEntries = new List <Entry>();

            // First pass to properly remove the correct value of fourier
            bool firstpass = false;

            int packetCount   = 0;
            int packetHSCount = 0;

            int elect1_0 = 0;
            int elect2_0 = 0;
            int elect1_1 = 0;
            int elect2_1 = 0;
            int elect1_2 = 0;
            int elect2_2 = 0;
            int elect1_3 = 0;
            int elect2_3 = 0;

            float thetaWave  = 0;
            float alphaWave  = 0;
            float betaWave   = 0;
            float totalPower = 0;

            CrossBluetoothLE.Current.Adapter.DeviceAdvertised += (s, e) =>
            {
                // Check if we are connected to our devices and workout is running
                if ((Guids._guids.HBConnected == true || Guids._guids.HSConnected == true) && finishBtn.IsEnabled)
                {
                    // Check if device is headband, headset, or not one of our devices
                    if (Guids._guids.HBConnected == true && Guids._guids.HeadbandGuid == e.Device.Id)
                    {
                        // Grab advertisements and process
                        Plugin.BLE.Abstractions.AdvertisementRecord[] advertisement = e.Device.AdvertisementRecords.ToArray();
                        //var temp = advertisement[3].Data[0];

                        if (advertisement.Length == 4)
                        {
                            elect1_0 = advertisement[3].Data[0] | (advertisement[3].Data[1] << 8);
                            elect2_0 = advertisement[3].Data[2] | (advertisement[3].Data[3] << 8);
                            elect1_1 = advertisement[3].Data[4] | (advertisement[3].Data[5] << 8);
                            elect2_1 = advertisement[3].Data[6] | (advertisement[3].Data[7] << 8);
                            elect1_2 = advertisement[3].Data[8] | (advertisement[3].Data[9] << 8);
                            elect2_2 = advertisement[3].Data[10] | (advertisement[3].Data[11] << 8);
                            elect1_3 = advertisement[3].Data[12] | (advertisement[3].Data[13] << 8);
                            elect2_3 = advertisement[3].Data[14] | (advertisement[3].Data[15] << 8);
                        }
                        else
                        {
                            elect1_0 = advertisement[1].Data[0] | (advertisement[1].Data[1] << 8);
                            elect2_0 = advertisement[1].Data[2] | (advertisement[1].Data[3] << 8);
                            elect1_1 = advertisement[1].Data[4] | (advertisement[1].Data[5] << 8);
                            elect2_1 = advertisement[1].Data[6] | (advertisement[1].Data[7] << 8);
                            elect1_2 = advertisement[1].Data[8] | (advertisement[1].Data[9] << 8);
                            elect2_2 = advertisement[1].Data[10] | (advertisement[1].Data[11] << 8);
                            elect1_3 = advertisement[1].Data[12] | (advertisement[1].Data[13] << 8);
                            elect2_3 = advertisement[1].Data[14] | (advertisement[1].Data[15] << 8);
                        }

                        int input0 = elect1_0 + elect2_0;
                        int input1 = elect1_1 + elect2_1;
                        int input2 = elect1_2 + elect2_2;
                        int input3 = elect1_3 + elect2_3;

                        // Remove at 0 position for our chart
                        if (chartEntries.Count > 100)
                        {
                            chartEntries.RemoveAt(0);
                        }

                        if (packetCount == 10)
                        {
                            // Add an entry with a title
                            entries.Add(new Entry(input0)
                            {
                                Color = SKColor.FromHsl(1, 100, 100, 255), ValueLabel = input0.ToString()
                            });
                            chartEntries.Add(new Entry(input0)
                            {
                                Color = SKColor.FromHsl(1, 100, 100, 255), ValueLabel = input0.ToString()
                            });

                            // Add the rest of the entries
                            entries.Add(new Entry(input1)
                            {
                                Color = SKColor.FromHsl(1, 100, 100, 255)
                            });
                            chartEntries.Add(new Entry(input1)
                            {
                                Color = SKColor.FromHsl(1, 100, 100, 255)
                            });
                            entries.Add(new Entry(input2)
                            {
                                Color = SKColor.FromHsl(1, 100, 100, 255)
                            });
                            chartEntries.Add(new Entry(input2)
                            {
                                Color = SKColor.FromHsl(1, 100, 100, 255)
                            });
                            entries.Add(new Entry(input3)
                            {
                                Color = SKColor.FromHsl(1, 100, 100, 255)
                            });
                            chartEntries.Add(new Entry(input3)
                            {
                                Color = SKColor.FromHsl(1, 100, 100, 255)
                            });

                            packetCount = 0;
                        }
                        else
                        {
                            entries.Add(new Entry(input0)
                            {
                                Color = SKColor.FromHsl(1, 100, 100, 255)
                            });
                            chartEntries.Add(new Entry(input0)
                            {
                                Color = SKColor.FromHsl(1, 100, 100, 255)
                            });
                            entries.Add(new Entry(input1)
                            {
                                Color = SKColor.FromHsl(1, 100, 100, 255)
                            });
                            chartEntries.Add(new Entry(input1)
                            {
                                Color = SKColor.FromHsl(1, 100, 100, 255)
                            });
                            entries.Add(new Entry(input2)
                            {
                                Color = SKColor.FromHsl(1, 100, 100, 255)
                            });
                            chartEntries.Add(new Entry(input2)
                            {
                                Color = SKColor.FromHsl(1, 100, 100, 255)
                            });
                            entries.Add(new Entry(input3)
                            {
                                Color = SKColor.FromHsl(1, 100, 100, 255)
                            });
                            chartEntries.Add(new Entry(input3)
                            {
                                Color = SKColor.FromHsl(1, 100, 100, 255)
                            });
                            packetCount++;
                        }

                        // Add values to our fourier list
                        headBandInput.Add(input0);
                        headBandInput.Add(input1);
                        headBandInput.Add(input2);
                        headBandInput.Add(input3);

                        var chart = new LineChart()
                        {
                            Entries         = chartEntries,
                            LabelTextSize   = 100,
                            LineSize        = 10,
                            LineMode        = LineMode.Straight,
                            PointSize       = 20,
                            BackgroundColor = SKColor.Parse("#393E46")
                        };
                        this.chartView.Chart = chart;

                        // Entries has reached max size
                        if (entries.Count > 250)
                        {
                            // Remove oldest values
                            while (headBandInput.Count > 250)
                            {
                                headBandInput.RemoveAt(0);
                                entries.RemoveAt(0);
                                chartEntries.RemoveAt(0);
                            }

                            // Perform fourier
                            Complex[] xt = ft.Transform(headBandInput);
                            for (int i = 1; i < 125; i++)
                            {
                                xt[i] = Meta.Numerics.ComplexMath.Abs(xt[i] * 2 / 250);
                                // Needed to not stack up fourier graphs
                                if (firstpass == true)
                                {
                                    fourierTransform.RemoveAt(0);
                                }
                                fourierTransform.Add(new Entry((float)xt[i])
                                {
                                    Color = SKColor.FromHsl(1, 100, 100, 255)
                                });
                            }
                            // Makes it so it doesn't remove the first value while it doesn't exsist.
                            firstpass = true;
                            var fChart = new LineChart()
                            {
                                Entries         = fourierTransform,
                                LabelTextSize   = 100,
                                LineSize        = 10,
                                LineMode        = LineMode.Straight,
                                PointSize       = 20,
                                BackgroundColor = SKColor.Parse("#393E46")
                            };
                            this.fourierChart.Chart = fChart;

                            totalPower = 0;
                            thetaWave  = 0;
                            alphaWave  = 0;
                            betaWave   = 0;
                            for (int n = 1; n < 125; n++)
                            {
                                if (n >= 30 && n <= 75)
                                {
                                    betaWave += (float)xt[n];
                                }
                                else if (n >= 20 && n < 30)
                                {
                                    alphaWave += (float)xt[n];
                                }
                                else if (n >= 5 && n < 20)
                                {
                                    thetaWave += (float)xt[n];
                                }
                                else
                                {
                                    totalPower += (float)xt[n];
                                }
                            }
                            if (barEntries.Count > 0)
                            {
                                barEntries.RemoveAt(0);
                                barEntries.RemoveAt(0);
                                barEntries.RemoveAt(0);
                                barEntries.RemoveAt(0);
                            }
                            barEntries.Add(new Entry(thetaWave)
                            {
                                Color = SKColor.Parse("#8B4B62"), ValueLabel = betaWave.ToString(), Label = "Sleepiness"
                            });
                            barEntries.Add(new Entry(alphaWave)
                            {
                                Color = SKColor.Parse("#BB6F6B"), ValueLabel = betaWave.ToString(), Label = "Relaxation"
                            });
                            barEntries.Add(new Entry(betaWave)
                            {
                                Color = SKColor.Parse("#FCBC80"), ValueLabel = betaWave.ToString(), Label = "Concentration"
                            });
                            barEntries.Add(new Entry(totalPower)
                            {
                                Color = SKColor.Parse("#EA9674"), ValueLabel = totalPower.ToString(), Label = "Other"
                            });
                            var barChart = new DonutChart
                            {
                                Entries         = barEntries,
                                BackgroundColor = SKColor.Parse("#393E46"),
                                LabelTextSize   = 40,
                            };
                            this.barGraphChart.Chart = barChart;
                        }
                    }
                    else if (Guids._guids.HSConnected == true && Guids._guids.HeadsetGuid == e.Device.Id)
                    {
                        Plugin.BLE.Abstractions.AdvertisementRecord[] advertisementHS = e.Device.AdvertisementRecords.ToArray();


                        // Geolocator
                        //packetTemp++;
                        //if (CrossGeolocator.IsSupported && IsLocationAvailable() && CrossGeolocator.Current.IsGeolocationEnabled && packetTemp == 10)
                        //{
                        //    double speed = await getSpeed();
                        //    speedEntries.Add(new Entry((float)speed) { Color = SKColor.FromHsl(1, 100, 100, 255), ValueLabel = speed.ToString() });
                        //    packetTemp = 0;

                        //    var speedChart = new LineChart()
                        //    {
                        //        Entries = speedEntries,
                        //        LabelTextSize = 100,
                        //        LineSize = 10,
                        //        LineMode = LineMode.Straight,
                        //        PointSize = 20,
                        //        BackgroundColor = SKColor.Parse("#393E46")
                        //    };
                        //    this.speedChart.Chart = speedChart;
                        //}


                        // Data variables
                        int tempHS = 0;
                        //int presHS = 0;
                        float accelX = 0;
                        float accelY = 0;
                        float accelZ = 0;
                        float gyX    = 0;
                        float gyY    = 0;
                        float gyZ    = 0;

                        if (advertisementHS.Length == 3)
                        {
                            tempHS = advertisementHS[2].Data[3] | (advertisementHS[2].Data[4] << 8);
                            accelX = advertisementHS[2].Data[5] | (advertisementHS[2].Data[6] << 8) | (advertisementHS[2].Data[7] << 16) | (advertisementHS[2].Data[8] << 24);
                            accelY = advertisementHS[2].Data[9] | (advertisementHS[2].Data[10] << 8) | (advertisementHS[2].Data[11] << 16) | (advertisementHS[2].Data[12] << 24);
                            accelZ = advertisementHS[2].Data[13] | (advertisementHS[2].Data[14] << 8) | (advertisementHS[2].Data[15] << 16) | (advertisementHS[2].Data[16] << 24);
                            gyX    = advertisementHS[2].Data[17] | (advertisementHS[2].Data[18] << 8) | (advertisementHS[2].Data[18] << 16) | (advertisementHS[2].Data[19] << 24);
                            gyY    = advertisementHS[2].Data[21] | (advertisementHS[2].Data[22] << 8) | (advertisementHS[2].Data[23] << 16) | (advertisementHS[2].Data[24] << 24);
                            gyZ    = advertisementHS[2].Data[25] | (advertisementHS[2].Data[26] << 8) | (advertisementHS[2].Data[27] << 16) | (advertisementHS[2].Data[28] << 24);
                            // presHS = advertisementHS[2].Data[29] | (advertisementHS[2].Data[30] << 8);
                        }
                        else
                        {
                            tempHS = advertisementHS[0].Data[3] | (advertisementHS[0].Data[4] << 8);
                            accelX = advertisementHS[0].Data[5] | (advertisementHS[0].Data[6] << 8) | (advertisementHS[0].Data[7] << 16) | (advertisementHS[0].Data[8] << 24);
                            accelY = advertisementHS[0].Data[9] | (advertisementHS[0].Data[10] << 8) | (advertisementHS[0].Data[11] << 16) | (advertisementHS[0].Data[12] << 24);
                            accelZ = advertisementHS[0].Data[13] | (advertisementHS[0].Data[14] << 8) | (advertisementHS[0].Data[15] << 16) | (advertisementHS[0].Data[16] << 24);
                            gyX    = advertisementHS[0].Data[17] | (advertisementHS[0].Data[18] << 8) | (advertisementHS[0].Data[18] << 16) | (advertisementHS[0].Data[19] << 24);
                            gyY    = advertisementHS[0].Data[21] | (advertisementHS[0].Data[22] << 8) | (advertisementHS[0].Data[23] << 16) | (advertisementHS[0].Data[24] << 24);
                            gyZ    = advertisementHS[0].Data[25] | (advertisementHS[0].Data[26] << 8) | (advertisementHS[0].Data[27] << 16) | (advertisementHS[0].Data[28] << 24);
                            // presHS = advertisementHS[0].Data[29] | (advertisementHS[0].Data[30] << 8);
                        }

                        // Bit parsing
                        tempHS = tempHS / 100;
                        // presHS = ((0x0142EE << 8) | presHS)/256;
                        accelX = accelX / 1000;
                        accelY = accelY / 1000;
                        accelZ = accelZ / 1000;
                        gyX    = gyX / 1000;
                        gyY    = gyY / 1000;
                        gyZ    = gyZ / 1000;

                        // When temperatureEntries is > 50 every HS data is >50 so remove first value
                        if (temperatureEntries.Count > 50)
                        {
                            temperatureEntries.RemoveAt(0);
                            accelXEntries.RemoveAt(0);
                            accelYEntries.RemoveAt(0);
                            accelZEntries.RemoveAt(0);
                            gyXEntries.RemoveAt(0);
                            gyYEntries.RemoveAt(0);
                            gyZEntries.RemoveAt(0);
                        }

                        // Adds data to each entry. If it is the 10th entry it adds a display value
                        if (packetHSCount == 10)
                        {
                            temperatureEntries.Add(new Entry(tempHS)
                            {
                                Color = SKColor.FromHsl(1, 100, 100, 255), ValueLabel = (tempHS).ToString()
                            });
                            accelXEntries.Add(new Entry((float)accelX)
                            {
                                Color = SKColor.FromHsl(1, 100, 100, 255), ValueLabel = ((float)accelX).ToString()
                            });
                            accelYEntries.Add(new Entry((float)accelY)
                            {
                                Color = SKColor.FromHsl(1, 100, 100, 255), ValueLabel = ((float)accelY).ToString()
                            });
                            accelZEntries.Add(new Entry((float)accelZ)
                            {
                                Color = SKColor.FromHsl(1, 100, 100, 255), ValueLabel = ((float)accelZ).ToString()
                            });
                            gyXEntries.Add(new Entry((float)gyX)
                            {
                                Color = SKColor.FromHsl(1, 100, 100, 255), ValueLabel = ((float)gyX).ToString()
                            });
                            gyYEntries.Add(new Entry((float)gyY)
                            {
                                Color = SKColor.FromHsl(1, 100, 100, 255), ValueLabel = ((float)gyY).ToString()
                            });
                            gyZEntries.Add(new Entry((float)gyZ)
                            {
                                Color = SKColor.FromHsl(1, 100, 100, 255), ValueLabel = ((float)gyZ).ToString()
                            });
                            // presEntries.Add(new Entry(presHS) { Color = SKColor.FromHsl(1, 100, 100, 255), ValueLabel = (presHS).ToString() });
                            packetHSCount = 0;
                        }
                        else
                        {
                            temperatureEntries.Add(new Entry(tempHS)
                            {
                                Color = SKColor.FromHsl(1, 100, 100, 255)
                            });
                            accelXEntries.Add(new Entry((float)accelX)
                            {
                                Color = SKColor.FromHsl(1, 100, 100, 255)
                            });
                            accelYEntries.Add(new Entry((float)accelY)
                            {
                                Color = SKColor.FromHsl(1, 100, 100, 255)
                            });
                            accelZEntries.Add(new Entry((float)accelZ)
                            {
                                Color = SKColor.FromHsl(1, 100, 100, 255)
                            });
                            gyXEntries.Add(new Entry((float)gyX)
                            {
                                Color = SKColor.FromHsl(1, 100, 100, 255)
                            });
                            gyYEntries.Add(new Entry((float)gyY)
                            {
                                Color = SKColor.FromHsl(1, 100, 100, 255)
                            });
                            gyZEntries.Add(new Entry((float)gyZ)
                            {
                                Color = SKColor.FromHsl(1, 100, 100, 255)
                            });
                            // presEntries.Add(new Entry(presHS) { Color = SKColor.FromHsl(1, 100, 100, 255) });
                            packetHSCount++;
                        }

                        // Declares the temperature chart
                        var tempChart = new LineChart()
                        {
                            Entries         = temperatureEntries,
                            LabelTextSize   = 100,
                            LineSize        = 10,
                            LineMode        = LineMode.Straight,
                            PointSize       = 20,
                            BackgroundColor = SKColor.Parse("#393E46")
                        };
                        this.temperatureChart.Chart = tempChart;

                        // Declares the accel x chart
                        var accelXChart = new LineChart()
                        {
                            Entries         = accelXEntries,
                            LabelTextSize   = 100,
                            LineSize        = 10,
                            LineMode        = LineMode.Straight,
                            PointSize       = 20,
                            BackgroundColor = SKColor.Parse("#393E46")
                        };
                        this.accelXChart.Chart = accelXChart;

                        var accelYChart = new LineChart()
                        {
                            Entries         = accelYEntries,
                            LabelTextSize   = 100,
                            LineSize        = 10,
                            LineMode        = LineMode.Straight,
                            PointSize       = 20,
                            BackgroundColor = SKColor.Parse("#393E46")
                        };
                        this.accelYChart.Chart = accelYChart;

                        var accelZChart = new LineChart()
                        {
                            Entries         = accelZEntries,
                            LabelTextSize   = 100,
                            LineSize        = 10,
                            LineMode        = LineMode.Straight,
                            PointSize       = 20,
                            BackgroundColor = SKColor.Parse("#393E46")
                        };
                        this.accelZChart.Chart = accelZChart;

                        var gyXChart = new LineChart()
                        {
                            Entries         = gyXEntries,
                            LabelTextSize   = 100,
                            LineSize        = 10,
                            LineMode        = LineMode.Straight,
                            PointSize       = 20,
                            BackgroundColor = SKColor.Parse("#393E46")
                        };
                        this.gyXChart.Chart = gyXChart;

                        var gyYChart = new LineChart()
                        {
                            Entries         = gyYEntries,
                            LabelTextSize   = 100,
                            LineSize        = 10,
                            LineMode        = LineMode.Straight,
                            PointSize       = 20,
                            BackgroundColor = SKColor.Parse("#393E46")
                        };
                        this.gyYChart.Chart = gyYChart;

                        var gyZChart = new LineChart()
                        {
                            Entries         = gyZEntries,
                            LabelTextSize   = 100,
                            LineSize        = 10,
                            LineMode        = LineMode.Straight,
                            PointSize       = 20,
                            BackgroundColor = SKColor.Parse("#393E46")
                        };
                        this.gyZChart.Chart = gyZChart;
                    }
                }
            };

            BindingContext = this;
        }
Beispiel #29
0
        // Every 1/60th second, update bitmap with user drawings
        bool OnTimerTick()
        {
            if (bitmap == null)
            {
                return(true);
            }

            // Determine the current color.
            float tColor = stopwatch.ElapsedMilliseconds % 10000 / 10000f;

            fingerPaint.Color    = SKColor.FromHsl(360 * tColor, 100, 50);
            titleLabel.TextColor = fingerPaint.Color.ToFormsColor();

            // Determine the rotation angle.
            float tAngle = stopwatch.ElapsedMilliseconds % 5000 / 5000f;

            angle = 360 * tAngle;
            SKMatrix matrix = SKMatrix.MakeRotationDegrees(-angle, bitmap.Width / 2, bitmap.Height / 2);

            // Loop trough the fingers touching the screen.
            foreach (long id in idDictionary.Keys)
            {
                FingerInfo fingerInfo = idDictionary[id];

                // Get the canvas size in pixels. It's square so it's only one number.
                float canvasSize = 0;

                if (canvasView is SKCanvasView)
                {
                    canvasSize = (canvasView as SKCanvasView).CanvasSize.Width;
                }
                else
                {
                    canvasSize = (canvasView as SKGLView).CanvasSize.Width;
                }

                // Convert Xamarin.Forms coordinates to pixels for drawing on the bitmap.
                // Also, make an offset factor if there's been resizing and the bitmap
                //      is now larger than the canvas. (It's never smaller.)
                float factor = canvasSize / (float)canvasView.Width;    // scaling factor
                float offset = (bitmapSize - canvasSize) / 2;           // bitmap always >= canvas

                SKPoint convertedPoint = new SKPoint(factor * (float)fingerInfo.ThisPosition.X + offset,
                                                     factor * (float)fingerInfo.ThisPosition.Y + offset);

                // Now rotate the point based on the rotation angle
                SKPoint pt0 = matrix.MapPoint(convertedPoint);

                if (!float.IsPositiveInfinity(fingerInfo.LastPosition.X))
                {
                    // Draw four lines in four quadrants.
                    SKPoint pt1 = fingerInfo.LastPosition;
                    bitmapCanvas.DrawLine(pt0.X, pt0.Y, pt1.X, pt1.Y, fingerPaint);

                    float x0Flip = bitmap.Width - pt0.X;
                    float y0Flip = bitmap.Height - pt0.Y;
                    float x1Flip = bitmap.Width - pt1.X;
                    float y1Flip = bitmap.Height - pt1.Y;

                    bitmapCanvas.DrawLine(x0Flip, pt0.Y, x1Flip, pt1.Y, fingerPaint);
                    bitmapCanvas.DrawLine(pt0.X, y0Flip, pt1.X, y1Flip, fingerPaint);
                    bitmapCanvas.DrawLine(x0Flip, y0Flip, x1Flip, y1Flip, fingerPaint);
                }

                // Save the current point for next time through.
                fingerInfo.LastPosition = pt0;
            }

            // Redraw the canvas.
            if (canvasView is SKCanvasView)
            {
                (canvasView as SKCanvasView).InvalidateSurface();
            }
            else
            {
                (canvasView as SKGLView).InvalidateSurface();
            }
            return(true);
        }
Beispiel #30
0
 public static SKColor Lighten(this SKColor color, DarkeningAmount amount = DarkeningAmount.Light)
 {
     color.ToHsl(out float h, out float s, out float l);
     return(SKColor.FromHsl(h, s, l + (int)amount > 100 ? 100 : l + (int)amount));
 }