Beispiel #1
0
        private void SKCanvasView_PaintSurface(object sender, SkiaSharp.Views.Forms.SKPaintSurfaceEventArgs e)
        {
            var canvas = e.Surface.Canvas;
            var height = canvas.DeviceClipBounds.Height;
            var width  = canvas.DeviceClipBounds.Width;

            var boxHeight = PageHeight * .2;
            var boxWidth  = PageWidth * .9;

            var vertices = new SKPoint[]
            {
                new SKPoint((float)width * .33f, 0f),
                new SKPoint((float)width * .66f, (float)height),
                new SKPoint((float)width, 0f),
            };

            var vertices1 = new SKPoint[]
            {
                new SKPoint((float)width * .5f, 0f),
                new SKPoint((float)width * .85f, (float)height + (float)height * .1f),
                new SKPoint((float)width + (float)width * .25f, 0f),
            };

            var offset = SKPoint.Distance(vertices[0], vertices[2]);

            var point1 = new SKPoint((float)width * .66f, (float)height);
            var point2 = new SKPoint((float)width * .85f, (float)height + (float)height * .1f);

            var distance = SKPoint.Distance(point1, point2);

            var midPoint = new SKPoint(point1.X + distance / 2, point1.Y - point1.Y * .20f);

            var vertices2 = new SKPoint[]
            {
                new SKPoint((float)width * .5f, 0f),
                midPoint,
                new SKPoint((float)width, 0f),
            };


            var triangleFill = new SKPaint()
            {
                Style = SKPaintStyle.StrokeAndFill,
                Color = SKColor.Parse("#00BE4F"),
            };

            canvas.Clear();

            canvas.Save();
            canvas.DrawRect(0f, 0f, (float)boxWidth, (float)boxHeight, rect);
            canvas.DrawVertices(SKVertexMode.Triangles, vertices, new SKColor[] { SKColor.Parse("#00BE4F"), SKColor.Parse("#00BE4F"), SKColor.Parse("#00BE4F") }, triangleFill);
            canvas.DrawVertices(SKVertexMode.Triangles, vertices1, new SKColor[] { SKColor.Parse("#00BE4F"), SKColor.Parse("#00BE4F"), SKColor.Parse("#00BE4F") }, triangleFill);
            canvas.DrawVertices(SKVertexMode.Triangles, vertices2, new SKColor[] { SKColor.Parse("#19C75D"), SKColor.Parse("#19C75D"), SKColor.Parse("#19C75D") }, triangleFill);
            canvas.Restore();
        }
        protected TanqueDetailViewModel(INavigationService navigationService,
                                        IPageDialogService pageDialogService, IFishTechAPIService FishTechService) : base(navigationService, pageDialogService)
        {
            _FishTechService   = FishTechService;
            _navigationService = navigationService;
            _pageDialogService = pageDialogService;
            phchart            = new BarChart();
            phchart.Entries    = new[]
            {
                new Entry(6.5f)
                {
                    Label      = "08/06/2019",
                    ValueLabel = "6.5",
                    Color      = SKColor.Parse("#FFA000")
                },
                new Entry(6.8f)
                {
                    Label      = "10/06/2019",
                    ValueLabel = "6.8",
                    Color      = SKColor.Parse("#D32F2F")
                },
                new Entry(5.9f)
                {
                    Label      = "11/06/2019",
                    ValueLabel = "5.9",
                    Color      = SKColor.Parse("#FFEB3B")
                },
                new Entry(4.7f)
                {
                    Label      = "12/06/2019",
                    ValueLabel = "4.7",
                    Color      = SKColor.Parse("#CDDC39")
                },
                new Entry(5.8f)
                {
                    Label      = "13/06/2019",
                    ValueLabel = "5.8",
                    Color      = SKColor.Parse("#FFEB3B")
                },
                new Entry(7.4f)
                {
                    Label      = "14/06/2019",
                    ValueLabel = "7.4",
                    Color      = SKColor.Parse("#D32F2F")
                },
                new Entry(7.4f)
                {
                    Label      = "15/06/2019",
                    ValueLabel = "7.4",
                    Color      = SKColor.Parse("#D32F2F")
                },
            };
            odchart = new LineChart()
            {
                LineMode  = LineMode.Spline,
                LineSize  = 8,
                PointMode = PointMode.Circle,
                PointSize = 18,
            };
            odchart.Entries = new[]
            {
                new Entry(36.1f)
                {
                    Label      = "08/06/2019",
                    ValueLabel = "36.1",
                    Color      = SKColor.Parse("#FFA000")
                },
                new Entry(37.1f)
                {
                    Label      = "10/06/2019",
                    ValueLabel = "37.1",
                    Color      = SKColor.Parse("#D32F2F")
                },
                new Entry(33.1f)
                {
                    Label      = "11/06/2019",
                    ValueLabel = "33.1",
                    Color      = SKColor.Parse("#FFEB3B")
                },
                new Entry(31.1f)
                {
                    Label      = "12/06/2019",
                    ValueLabel = "31.1",
                    Color      = SKColor.Parse("#CDDC39")
                },
                new Entry(36.1f)
                {
                    Label      = "13/06/2019",
                    ValueLabel = "36.1",
                    Color      = SKColor.Parse("#FFEB3B")
                },
                new Entry(39.1f)
                {
                    Label      = "14/06/2019",
                    ValueLabel = "39.1",
                    Color      = SKColor.Parse("#D32F2F")
                },
                new Entry(36.1f)
                {
                    Label      = "15/06/2019",
                    ValueLabel = "36.1",
                    Color      = SKColor.Parse("#FFA000")
                },
            };

            tempchart = new PointChart()
            {
                PointMode = PointMode.Square,
                MaxValue  = 36.5f,
                MinValue  = 33.5f
            };
            tempchart.Entries = new[]
            {
                new Entry(33.1f)
                {
                    Label      = "09/06/2019",
                    ValueLabel = "33.1",
                    Color      = SKColor.Parse("#CDDC39")
                },
                new Entry(34.1f)
                {
                    Label      = "10/06/2019",
                    ValueLabel = "34.1",
                    Color      = SKColor.Parse("#CDDC39")
                },
                new Entry(34.8f)
                {
                    Label      = "11/06/2019",
                    ValueLabel = "34.1",
                    Color      = SKColor.Parse("#FFEB3B")
                },
                new Entry(34.8f)
                {
                    Label      = "12/06/2019",
                    ValueLabel = "34.8",
                    Color      = SKColor.Parse("#FFEB3B")
                },
                new Entry(35.6f)
                {
                    Label      = "13/06/2019",
                    ValueLabel = "35.6",
                    Color      = SKColor.Parse("#FFEB3B")
                },
                new Entry(36.2f)
                {
                    Label      = "14/06/2019",
                    ValueLabel = "36.2",
                    Color      = SKColor.Parse("#D32F2F")
                },
                new Entry(36.8f)
                {
                    Label      = "15/06/2019",
                    ValueLabel = "36.8",
                    Color      = SKColor.Parse("#D32F2F")
                },
            };
            turbidezchart = new LineChart()
            {
                LineMode  = LineMode.Straight,
                LineSize  = 8,
                PointMode = PointMode.Square,
                PointSize = 18,
            };
            turbidezchart.Entries = new[]
            {
                new Entry(33.1f)
                {
                    Label      = "09/06/2019",
                    ValueLabel = "33.1",
                    Color      = SKColor.Parse("#CDDC39")
                },
                new Entry(34.1f)
                {
                    Label      = "10/06/2019",
                    ValueLabel = "34.1",
                    Color      = SKColor.Parse("#CDDC39")
                },
                new Entry(34.8f)
                {
                    Label      = "11/06/2019",
                    ValueLabel = "34.1",
                    Color      = SKColor.Parse("#FFEB3B")
                },
                new Entry(34.8f)
                {
                    Label      = "12/06/2019",
                    ValueLabel = "34.8",
                    Color      = SKColor.Parse("#FFEB3B")
                },
                new Entry(35.6f)
                {
                    Label      = "13/06/2019",
                    ValueLabel = "35.6",
                    Color      = SKColor.Parse("#FFEB3B")
                },
                new Entry(36.2f)
                {
                    Label      = "14/06/2019",
                    ValueLabel = "36.2",
                    Color      = SKColor.Parse("#D32F2F")
                },
                new Entry(36.8f)
                {
                    Label      = "15/06/2019",
                    ValueLabel = "36.8",
                    Color      = SKColor.Parse("#D32F2F")
                },
            };
        }
Beispiel #3
0
        public void calculateWeeks()
        {
            try {
                btnNext.IsEnabled = true;
                Double initialWeight = Convert.ToDouble(txtInitialWeigh.Text);
                Double finalWeight   = Convert.ToDouble(txtFinalWeight.Text);
                double test          = initialWeight - ((initialWeight - finalWeight) / 2);
                Double TotalWeeks;


                if (myValue == 0 && initialWeight > finalWeight)

                {
                    TotalWeeks     = (initialWeight - finalWeight) / 0.5;
                    lblResult.Text = "You require an estimate maximum of " + TotalWeeks.ToString() + " weeks in order to achieve your weight goal, losing a total ammount of: " + (initialWeight - finalWeight).ToString() + " Kilograms";
                    lblNext.Text   = "The next you need to do is calculate your daily calories using the Daily Calories calculator in order to be able to consume less calories than you burn. Press " +
                                     "the Next Button to go there";

                    List <Entry> entries = new List <Entry>
                    {
                        new Entry(Convert.ToInt32(initialWeight))
                        {
                            Color      = SKColor.Parse("#a256ff"),
                            Label      = "Week 0",
                            ValueLabel = initialWeight.ToString(),
                        },

                        new Entry(Convert.ToInt32(test))
                        {
                            Color      = SKColor.Parse("#a256ff"),
                            Label      = "Week " + (TotalWeeks / 2).ToString(),
                            ValueLabel = test.ToString(),
                        },



                        new Entry(Convert.ToInt32(finalWeight))
                        {
                            Color      = SKColor.Parse("#a256ff"),
                            Label      = "Week " + TotalWeeks.ToString(),
                            ValueLabel = finalWeight.ToString(),
                        },
                    };

                    Chart2.Chart = new LineChart {
                        Entries = entries, LabelTextSize = 15
                    };
                }

                else if (myValue == 2 && finalWeight > initialWeight)
                {
                    TotalWeeks     = (finalWeight - initialWeight) / 0.5;
                    lblResult.Text = "You require an estimate maximum of " + TotalWeeks.ToString() + " weeks in order to achieve your weight goal, gaining a total ammount of: " + (finalWeight - initialWeight).ToString() + " Kilograms";
                    lblNext.Text   = "The next you need to do is calculate your daily calories using the Daily Calories calculator in order to be able to consume more calories than you burn. Press " +
                                     "the Next Button to go there";
                }
                else
                {
                    DisplayAlert("Incorrect details", "Your weight details are incorrect, please submit them again. Also check the goal selector incase you have the wrong type selected", "Okay");
                }
            }
            catch
            {
                DisplayAlert("Incorrect details", "You are missing details or wrong format", "OK");
            }
        }
        async void Refresh()
        {
            try
            {
                string url = "https://covid19-api.org/api/timeline";
                using (var client = new HttpClient())
                {
                    Uri uri = new Uri(string.Format(url, string.Empty));
                    HttpResponseMessage response = await client.GetAsync(uri);

                    if (response.IsSuccessStatusCode)
                    {
                        entries = new List <ChartEntry>();
                        string content = await response.Content.ReadAsStringAsync();

                        var items  = JsonConvert.DeserializeObject <GlobalStats[]>(content);
                        var realit = items.Take(14);
                        ct             = realit.First();
                        BindingContext = ct;
                        newdeath.Text  = (realit.ElementAt(0).total_deaths - realit.ElementAt(1).total_deaths).ToString("N0");
                        newinfec.Text  = (realit.ElementAt(0).total_cases - realit.ElementAt(1).total_cases).ToString("N0");
                        newrec.Text    = (realit.ElementAt(0).total_recovered - realit.ElementAt(1).total_recovered).ToString("N0");
                        foreach (var item in realit.Reverse())
                        {
                            entries.Add(new ChartEntry(item.total_cases)
                            {
                                Label = item.last_update.ToString("MMM dd"), ValueLabel = item.total_cases.ToString(), Color = SKColor.Parse("#FB4D4F")
                            });
                        }
                    }
                }
                TotalCases.Chart = new LineChart()
                {
                    Entries = entries, LineMode = LineMode.Straight, LabelTextSize = 32, MinValue = entries.ElementAt(0).Value - 1000000
                };
            }
            catch
            {
                await DisplayAlert("Error", "Check Your Internet Connection" + Application.Current.Properties["Country"], "ok");
            }
        }
        private async Task <IEnumerable <Microcharts.Entry> > GetEntriesAsync()
        {
            var currentTime = DateTime.Now;
            List <Microcharts.Entry> entries = new List <Microcharts.Entry>();

            if (OfertasTabDetailPageViewModel.Oferta != null)
            {
                var index     = 1;
                var historico = await ofertasService.CarregarHistoricoDeOFertaAsync(OfertasTabDetailPageViewModel.Oferta.Id, FromDate, UntilDate);

                historico.Select(x =>
                {
                    if (index == 1 || index == Math.Round(historico.Count() / 2M, 0, MidpointRounding.ToEven) || index == historico.Count())
                    {
                        entries.Add(new Microcharts.Entry((float)x.Preco)
                        {
                            Label      = ObterDescriptionDateTime(x.UpdatedAt), // "January",
                            ValueLabel = $"R$ {x.Preco}",                       //"102",
                            Color      = SKColor.Parse("#4e6cab"),
                            TextColor  = SKColor.Parse("#4e6cab"),
                        });
                    }
                    else
                    {
                        entries.Add(new Microcharts.Entry((float)x.Preco)
                        {
                            Color     = SKColor.Parse("#4e6cab"),
                            TextColor = SKColor.Parse("#4e6cab"),
                            Label     = null,
                        });
                    }
                    index++;
                    return(x);
                }).ToArray();
                return(entries);
            }
            return(null);

            string ObterDescriptionDateTime(DateTime date)
            {
                var difference = (currentTime - date);

                if (difference.TotalDays < 1)
                {
                    if (difference.TotalHours < 1)
                    {
                        var minutos      = Math.Round(difference.TotalMinutes, 0);
                        var minutoString = minutos > 1 ? "minutos" : "minuto";
                        return($"Há {minutos} {minutoString}");
                    }
                    else
                    {
                        var horas       = Math.Round(difference.TotalHours, 0);
                        var horasString = horas > 1 ? "horas" : "hora";
                        return($"Há {horas} {horasString}");
                    }
                }
                else
                {
                    var dias       = Math.Round(difference.TotalDays, 0);
                    var diasString = dias > 1 ? "dias" : "dia";
                    return($"Há {dias} {diasString}");
                }
            }
        }
Beispiel #6
0
        private void InitLineChart()
        {
            linePiezo = linePiezo ??
                        new LineChart()
            {
                Entries               = queuePiezo,
                LabelOrientation      = Orientation.Vertical,
                ValueLabelOrientation = Orientation.Horizontal,
                MinValue              = 0,
                MaxValue              = MaxValue,
                IsAnimated            = false,
                LineAreaAlpha         = 0,
                PointSize             = 6,
                LabelTextSize         = 10,
                LineMode              = LineMode.Spline,
                BackgroundColor       = SKColor.Empty,
                LabelColor            = SKColor.Parse("#000000")
            };
            lineAx = lineAx ??
                     new LineChart()
            {
                Entries               = queueAx,
                LabelOrientation      = Orientation.Vertical,
                ValueLabelOrientation = Orientation.Horizontal,
                MinValue              = 0,
                MaxValue              = MaxValue,
                IsAnimated            = false,
                LineAreaAlpha         = 0,
                PointSize             = 6,
                LabelTextSize         = 10,
                LineMode              = LineMode.Spline,
                BackgroundColor       = SKColor.Empty,
                LabelColor            = SKColor.Empty
            };
            lineAy = lineAy ??
                     new LineChart()
            {
                Entries               = queueAy,
                LabelOrientation      = Orientation.Vertical,
                ValueLabelOrientation = Orientation.Horizontal,
                MinValue              = 0,
                MaxValue              = MaxValue,
                IsAnimated            = false,
                LineAreaAlpha         = 0,
                PointSize             = 6,
                LabelTextSize         = 10,
                LineMode              = LineMode.Spline,
                BackgroundColor       = SKColor.Empty,
                LabelColor            = SKColor.Empty
            };

            lineAz = lineAz ??
                     new LineChart()
            {
                Entries               = queueAz,
                LabelOrientation      = Orientation.Vertical,
                ValueLabelOrientation = Orientation.Horizontal,
                MinValue              = 0,
                MaxValue              = MaxValue,
                IsAnimated            = false,
                LineAreaAlpha         = 0,
                PointSize             = 6,
                LabelTextSize         = 10,
                LineMode              = LineMode.Spline,
                BackgroundColor       = SKColor.Empty,
                LabelColor            = SKColor.Parse("#000000")
            };
        }
        protected override bool OnDraw(SciterElement se, DrawArgs args)
        {
            if (args.DrawEvent == DrawEvent.Background)
            {
                using (SKBitmap bitmap = new SKBitmap(width: args.Area.Width, height: args.Area.Height, colorType: SKColorType.Rgba8888, alphaType: SKAlphaType.Premul))
                    using (SKCanvas canvas = new SKCanvas(bitmap))
                        using (SKPaint paint = new SKPaint())
                        {
                            paint.IsAntialias = true;

                            canvas.Clear();

                            paint.Shader = SKShader.CreateLinearGradient(
                                //new SKPoint(prms.area.Width / 2f, prms.area.Height / 2f),
                                new SKPoint(0, 0),
                                new SKPoint(args.Area.Width, args.Area.Height),
                                //Math.Max(prms.area.Width, prms.area.Height) / 10f,
                                new SKColor[] { SKColor.Parse("#FF75B7FE"), SKColor.Parse("#00000000") },
                                null,
                                SKShaderTileMode.Clamp);

                            canvas.DrawRect(new SKRect(0, 0, args.Area.Width, args.Area.Height), paint);

                            var img = bitmap.ToSciterImage();
                            var gfx = SciterGraphics.Create(args.Handle);
                            gfx.BlendImage(img, args.Area.Left, args.Area.Top);
                            //return true;
                        }

                //// set up drawing tools
                //using (var paint = new SKPaint())
                //{
                //    paint.IsAntialias = true;
                //    paint.Color = new SKColor(127, 78, 194, 50);
                //    paint.StrokeCap = SKStrokeCap.Round;

                //    // create the Xamagon path
                //    using (var path = new SKPath())
                //    {
                //        path.MoveTo(71.4311121f, 56f);
                //        path.CubicTo(68.6763107f, 56.0058575f, 65.9796704f, 57.5737917f, 64.5928855f, 59.965729f);
                //        path.LineTo(43.0238921f, 97.5342563f);
                //        path.CubicTo(41.6587026f, 99.9325978f, 41.6587026f, 103.067402f, 43.0238921f, 105.465744f);
                //        path.LineTo(64.5928855f, 143.034271f);
                //        path.CubicTo(65.9798162f, 145.426228f, 68.6763107f, 146.994582f, 71.4311121f, 147f);
                //        path.LineTo(114.568946f, 147f);
                //        path.CubicTo(117.323748f, 146.994143f, 120.020241f, 145.426228f, 121.407172f, 143.034271f);
                //        path.LineTo(142.976161f, 105.465744f);
                //        path.CubicTo(144.34135f, 103.067402f, 144.341209f, 99.9325978f, 142.976161f, 97.5342563f);
                //        path.LineTo(121.407172f, 59.965729f);
                //        path.CubicTo(120.020241f, 57.5737917f, 117.323748f, 56.0054182f, 114.568946f, 56f);
                //        path.LineTo(71.4311121f, 56f);
                //        path.Close();

                //        // draw the Xamagon path
                //        canvas.DrawPath(path, paint);
                //    }

                //    paint.Color = new SKColor(255, 255, 255);
                //    paint.TextSize = 24f;
                //    canvas.DrawText("Hello from SkiaSharp", 0, 5 * b.Height / 6, paint);
                //}

                //var b = new Image(406, 400);
                //using (var g = System.Drawing.Graphics.FromImage(b))
                //{
                //	LinearGradientBrush linGrBrush = new LinearGradientBrush(
                //		new Point(0, 10),
                //		new Point(200, 10),
                //		Color.FromArgb(255, 255, 0, 0),   // Opaque red
                //		Color.FromArgb(255, 0, 0, 255));  // Opaque blue
                //	g.SmoothingMode = SmoothingMode.AntiAlias;
                //	g.FillEllipse(linGrBrush, 0, 30, 200, 100);
                //}
            }

            return(base.OnDraw(se, args));
        }
Beispiel #8
0
        private static void DrawImagesOnCanvasInternal(
            SKCanvas canvas, SKBitmap leftBitmap, SKBitmap rightBitmap,
            int borderThickness, bool addBorder, BorderColor borderColor,
            double leftLeftCrop, double leftRightCrop, double rightLeftCrop, double rightRightCrop,
            double topCrop, double bottomCrop,
            float leftRotation, float rightRotation, double alignment,
            double leftZoom, double rightZoom,
            float leftKeystone, float rightKeystone,
            DrawMode drawMode)
        {
            if (leftBitmap == null && rightBitmap == null)
            {
                return;
            }

            var canvasWidth  = canvas.DeviceClipBounds.Width;
            var canvasHeight = canvas.DeviceClipBounds.Height;

            int leftBitmapWidthLessCrop;
            int leftBitmapHeightLessCrop;

            if (leftBitmap != null)
            {
                leftBitmapWidthLessCrop  = (int)(leftBitmap.Width - leftBitmap.Width * (leftLeftCrop + leftRightCrop));
                leftBitmapHeightLessCrop = (int)(leftBitmap.Height - leftBitmap.Height * (topCrop + bottomCrop + Math.Abs(alignment)));
            }
            else
            {
                leftBitmapWidthLessCrop  = (int)(rightBitmap.Width - rightBitmap.Width * (rightLeftCrop + rightRightCrop));
                leftBitmapHeightLessCrop = (int)(rightBitmap.Height - rightBitmap.Height * (topCrop + bottomCrop + Math.Abs(alignment))); //TODO: why did this become just one side? was it abandoned incomplete work?
            }

            var innerBorderThicknessProportion = leftBitmap != null &&
                                                 rightBitmap != null &&
                                                 addBorder &&
                                                 drawMode != DrawMode.RedCyanAnaglyph &&
                                                 drawMode != DrawMode.GrayscaleRedCyanAnaglyph ?
                                                 BORDER_CONVERSION_FACTOR * borderThickness :
                                                 0;

            var widthRatio = (leftBitmapWidthLessCrop + leftBitmapWidthLessCrop * innerBorderThicknessProportion * 1.5) / (canvasWidth / 2f);

            if (drawMode == DrawMode.RedCyanAnaglyph ||
                drawMode == DrawMode.GrayscaleRedCyanAnaglyph)
            {
                widthRatio /= 2;
            }
            var heightRatio  = (leftBitmapHeightLessCrop + leftBitmapWidthLessCrop * innerBorderThicknessProportion * 2) / (1f * canvasHeight);
            var scalingRatio = widthRatio > heightRatio ? widthRatio : heightRatio;

            float leftPreviewX;
            float rightPreviewX;
            float previewY;
            var   sidePreviewWidthLessCrop = (float)(leftBitmapWidthLessCrop / scalingRatio);
            var   previewHeightLessCrop    = (float)(leftBitmapHeightLessCrop / scalingRatio);

            switch (drawMode)
            {
            case DrawMode.GrayscaleRedCyanAnaglyph:
            case DrawMode.RedCyanAnaglyph:
                leftPreviewX = rightPreviewX = canvasWidth / 2f - sidePreviewWidthLessCrop / 2f;
                previewY     = canvasHeight / 2f - previewHeightLessCrop / 2f;
                break;

            default:
                leftPreviewX  = (float)(canvasWidth / 2f - sidePreviewWidthLessCrop - innerBorderThicknessProportion * sidePreviewWidthLessCrop / 2f);
                rightPreviewX = (float)(canvasWidth / 2f + innerBorderThicknessProportion * sidePreviewWidthLessCrop / 2f);
                previewY      = canvasHeight / 2f - previewHeightLessCrop / 2f;
                break;
            }
            var isRightRotated   = Math.Abs(rightRotation) > FLOATY_ZERO;
            var isLeftRotated    = Math.Abs(leftRotation) > FLOATY_ZERO;
            var isRightKeystoned = Math.Abs(rightKeystone) > FLOATY_ZERO;
            var isLeftKeystoned  = Math.Abs(leftKeystone) > FLOATY_ZERO;

            if (leftBitmap != null)
            {
                SKBitmap grayscale = null;
                if (drawMode == DrawMode.GrayscaleRedCyanAnaglyph)
                {
                    grayscale = FilterToGrayscale(leftBitmap);
                }

                SKBitmap transformed = null;
                if (isLeftRotated ||
                    leftZoom > 0 ||
                    isLeftKeystoned)
                {
                    transformed = ZoomAndRotate(grayscale ?? leftBitmap, leftZoom, isLeftRotated, leftRotation, isLeftKeystoned, -leftKeystone);
                }

                using (var paint = new SKPaint())
                {
                    if (drawMode == DrawMode.RedCyanAnaglyph ||
                        drawMode == DrawMode.GrayscaleRedCyanAnaglyph)
                    {
                        paint.ColorFilter =
                            SKColorFilter.CreateColorMatrix(new float[]
                        {
                            0, 0, 0, 0, 0,
                            0, 1, 0, 0, 0,
                            0, 0, 1, 0, 0,
                            0, 0, 0, 1, 0
                        });
                    }

                    var width  = transformed?.Width ?? grayscale?.Width ?? leftBitmap.Width;
                    var height = transformed?.Height ?? grayscale?.Height ?? leftBitmap.Height;

                    canvas.DrawBitmap(
                        transformed ?? grayscale ?? leftBitmap,
                        SKRect.Create(
                            (float)(width * leftLeftCrop),
                            (float)(height * topCrop + (alignment > 0 ? alignment * height : 0)),
                            (float)(width - width * (leftLeftCrop + leftRightCrop)),
                            (float)(height - height * (topCrop + bottomCrop + Math.Abs(alignment)))),
                        SKRect.Create(
                            leftPreviewX,
                            previewY,
                            sidePreviewWidthLessCrop,
                            previewHeightLessCrop),
                        paint);
                }

                grayscale?.Dispose();
                transformed?.Dispose();
            }

            if (rightBitmap != null)
            {
                SKBitmap grayscale = null;
                if (drawMode == DrawMode.GrayscaleRedCyanAnaglyph)
                {
                    grayscale = FilterToGrayscale(rightBitmap);
                }

                SKBitmap transformed = null;
                if (isRightRotated ||
                    rightZoom > 0 ||
                    isRightKeystoned)
                {
                    transformed = ZoomAndRotate(grayscale ?? rightBitmap, rightZoom, isRightRotated, rightRotation, isRightKeystoned, rightKeystone);
                }

                using (var paint = new SKPaint())
                {
                    if (drawMode == DrawMode.RedCyanAnaglyph ||
                        drawMode == DrawMode.GrayscaleRedCyanAnaglyph)
                    {
                        paint.ColorFilter =
                            SKColorFilter.CreateColorMatrix(new float[]
                        {
                            1, 0, 0, 0, 0,
                            0, 0, 0, 0, 0,
                            0, 0, 0, 0, 0,
                            0, 0, 0, 1, 0
                        });
                        paint.BlendMode = SKBlendMode.Plus;
                    }

                    var width  = transformed?.Width ?? grayscale?.Width ?? rightBitmap.Width;
                    var height = transformed?.Height ?? grayscale?.Height ?? rightBitmap.Height;

                    canvas.DrawBitmap(
                        transformed ?? grayscale ?? rightBitmap,
                        SKRect.Create(
                            (float)(width * rightLeftCrop),
                            (float)(height * topCrop - (alignment < 0 ? alignment * height : 0)),
                            (float)(width - width * (rightLeftCrop + rightRightCrop)),
                            (float)(height - height * (topCrop + bottomCrop + Math.Abs(alignment)))),
                        SKRect.Create(
                            rightPreviewX,
                            previewY,
                            sidePreviewWidthLessCrop,
                            previewHeightLessCrop),
                        paint);
                }

                grayscale?.Dispose();
                transformed?.Dispose();
            }

            if (innerBorderThicknessProportion > 0)
            {
                var borderPaint = new SKPaint
                {
                    Color = borderColor == BorderColor.Black ? SKColor.Parse("000000") : SKColor.Parse("ffffff"),
                    Style = SKPaintStyle.StrokeAndFill
                };

                var originX               = (float)(leftPreviewX - innerBorderThicknessProportion * sidePreviewWidthLessCrop);
                var originY               = (float)(previewY - innerBorderThicknessProportion * sidePreviewWidthLessCrop);
                var fullPreviewWidth      = (float)(2 * sidePreviewWidthLessCrop + 3 * innerBorderThicknessProportion * sidePreviewWidthLessCrop);
                var fullPreviewHeight     = (float)(previewHeightLessCrop + 2 * innerBorderThicknessProportion * sidePreviewWidthLessCrop);
                var scaledBorderThickness = (float)(innerBorderThicknessProportion * sidePreviewWidthLessCrop);
                var endX = rightPreviewX + sidePreviewWidthLessCrop;
                var endY = previewY + previewHeightLessCrop;
                canvas.DrawRect(originX, originY, fullPreviewWidth, scaledBorderThickness, borderPaint);
                canvas.DrawRect(originX, originY, scaledBorderThickness, fullPreviewHeight, borderPaint);
                canvas.DrawRect(canvasWidth / 2f - scaledBorderThickness / 2f, originY, scaledBorderThickness, fullPreviewHeight, borderPaint);
                canvas.DrawRect(endX, originY, scaledBorderThickness, fullPreviewHeight, borderPaint);
                canvas.DrawRect(originX, endY, fullPreviewWidth, scaledBorderThickness, borderPaint);
            }
        }
Beispiel #9
0
        public static void Chart(Grid grid, int px, int py, int sx, int sy, string header, JObject data)
        {
            Microsoft.AppCenter.Analytics.Analytics.TrackEvent("Create Chart Widget");
            CrossLogger.Current.Debug("Chart", "Creating Chart Widget");

            try
            {
                Models.Sitemap.Widget3 item = data.ToObject <Models.Sitemap.Widget3>();
                //List<Models.Sitemap.Widget3> items = data.ToObject<List<Models.Sitemap.Widget3>>();


                #region w_grid
                Grid w_grid = new Grid
                {
                    Padding           = new Thickness(0, 0, 0, 0),
                    RowSpacing        = 0,
                    ColumnSpacing     = 0,
                    BackgroundColor   = App.Config.CellColor,
                    VerticalOptions   = LayoutOptions.FillAndExpand,
                    HorizontalOptions = LayoutOptions.FillAndExpand,
                    RowDefinitions    = new RowDefinitionCollection
                    {
                        new RowDefinition {
                            Height = new GridLength(1, GridUnitType.Star)
                        },
                        new RowDefinition {
                            Height = GridLength.Auto
                        },
                    },
                    ColumnDefinitions = new ColumnDefinitionCollection
                    {
                        new ColumnDefinition {
                            Width = new GridLength(1, GridUnitType.Star)
                        },
                    },
                };
                grid.Children.Add(w_grid, px, px + sx, py, py + sy);
                #endregion w_grid


                List <Entry> entries = new List <Entry>
                {
                    new Entry(200)
                    {
                        Label      = "January",
                        ValueLabel = "200",
                        Color      = SKColor.Parse("#266489")
                    },
                    new Entry(400)
                    {
                        Label      = "February",
                        ValueLabel = "400",
                        Color      = SKColor.Parse("#68B9C0")
                    },
                    new Entry(-100)
                    {
                        Label      = "March",
                        ValueLabel = "-100",
                        Color      = SKColor.Parse("#90D585")
                    }
                };
                var cv = new ChartView();
                cv.Chart = new BarChart()
                {
                    Entries = entries
                };

                // or: var chart = new PointChart() { Entries = entries };
                // or: var chart = new LineChart() { Entries = entries };
                // or: var chart = new DonutChart() { Entries = entries };
                // or: var chart = new RadialGaugeChart() { Entries = entries };
                // or: var chart = new RadarChart() { Entries = entries };

                #region Button
                Button dummyButton = new Button
                {
                    HorizontalOptions = LayoutOptions.FillAndExpand,
                    VerticalOptions   = LayoutOptions.FillAndExpand,
                    BackgroundColor   = Color.Transparent,
                };
                grid.Children.Add(dummyButton, px, px + sx, py, py + sy);
                dummyButton.Clicked += OnDummyButtonClicked;
                #endregion Button
            }
            catch (Exception ex)
            {
                CrossLogger.Current.Error("Chart", "Crashed: " + ex.ToString());
                Error(grid, px, py, 1, 1, ex.ToString());
            }
        }
Beispiel #10
0
        public static Stream MakePatientPercentileChart(TestResultGroup testResultGroup)
        {
            var entries = new List <Entry>();

            int[]  green  = new int[] { 0, 255, 0 };
            int[]  yellow = new int[] { 255, 255, 0 };
            int[]  red    = new int[] { 255, 0, 0 };
            double interp;
            string hexcol;
            int    percentile;

            foreach (TestResult result in testResultGroup.Tests)
            {
                interp = 0.01 * result.Percentile;
                if (interp < 0.5)
                {
                    hexcol = ColToHex(LinearInterpolation(red, yellow, 2 * interp));
                }
                else
                {
                    hexcol = ColToHex(LinearInterpolation(yellow, green, 2 * (interp - 0.5)));
                }
                if (Math.Abs(result.Percentile) < 1)
                {
                    percentile = 1;
                }
                else
                {
                    percentile = (int)result.Percentile;
                }
                entries.Add(new Entry(percentile)
                {
                    Label      = result.Test.Name,
                    ValueLabel = result.Percentile.ToString(),
                    Color      = SKColor.Parse(hexcol)
                });
            }

            var chart = new BarChart()
            {
                Entries          = entries,
                MaxValue         = 100,
                MinValue         = 0,
                LabelOrientation = Microcharts.Orientation.Vertical
            };

            int width  = entries.Count * 50;
            int height = 600;

            SKImageInfo info    = new SKImageInfo(width, height);
            SKSurface   surface = SKSurface.Create(info);

            SKCanvas canvas = surface.Canvas;

            chart.Draw(canvas, width, height);

            Stream imageStream = new MemoryStream();

            // create an image and then get the PNG (or any other) encoded data
            using (var data = surface.Snapshot().Encode(SKEncodedImageFormat.Png, 80)) {
                // save the data to a stream
                data.SaveTo(imageStream);
            }

            imageStream = RotateImage(imageStream);

            return(imageStream);
        }
        private async void StartUp()
        {
            try
            {
                imgHeart.Source  = "heart.png";
                imgHeart2.Source = "heart.png";
                imgHeart3.Source = "heart.png";

                if (Evaluatie.data.Count != 0)
                {
                    List <Microcharts.Entry> lstentries = new List <Microcharts.Entry>();
                    foreach (var item in Evaluatie.data)//data.HeartRate)
                    {
                        if (item > 50 && item < 180)
                        {
                            if (item < 100)
                            {
                                lstentries.Add(new Microcharts.Entry(item)
                                {
                                    Color = SKColor.Parse("#FFDC00")
                                });
                            }
                            else if (item > 120)
                            {
                                lstentries.Add(new Microcharts.Entry(item)
                                {
                                    Color = SKColor.Parse("#FF4136")
                                });
                            }
                            else
                            {
                                lstentries.Add(new Microcharts.Entry(item)
                                {
                                    Color = SKColor.Parse("#FF851B")
                                });
                            }
                        }
                    }
                    var chart = new LineChart()
                    {
                        Entries = lstentries, LineAreaAlpha = 1, LineMode = LineMode.Straight
                    };
                    chart.PointMode      = PointMode.None;
                    chart.LineSize       = 6;
                    chart.MinValue       = Evaluatie.data.Min();
                    this.chartView.Chart = chart;

                    lblMax.Text     = Evaluatie.data.Max().ToString();
                    lblMaxZone.Text = Evaluatie.data.Max().ToString();
                    lblMin.Text     = Evaluatie.data.Min().ToString();
                    lblMinZone.Text = Evaluatie.data.Min().ToString();
                    lblAvg.Text     = ((int)Evaluatie.data.Average()).ToString();
                }
                lblSet1.Text  = Evaluatie.Set1.ToString();
                lblSet2.Text  = Evaluatie.Set2.ToString();
                lblSet3.Text  = Evaluatie.Set3.ToString();
                Title         = "Evaluatie " + Evaluatie.Datum.Date.ToString("dd/MM/yyyy");
                lblDatum.Text = Evaluatie.Datum.ToString();
            }
            catch (Exception ex)
            {
                await StepOutManager.Writelog(ex);
                await DisplayAlert("Fout", "Er is iets misgelopen bij het tonen van de hartslag grafiek, als deze fout zich blijft voordoen neemt men best contact op met de support", "OK");
            }
        }
Beispiel #12
0
        private void GetData()
        {
            _timeEntries          = new List <Entry>();
            _timeByDayEntries     = new List <Entry>();
            _distanceEntries      = new List <Entry>();
            _distanceByDayEntries = new List <Entry>();


            Dictionary <string, int>      time          = new Dictionary <string, int>();
            Dictionary <string, double>   distance      = new Dictionary <string, double>();
            Dictionary <DateTime, int>    timeByDay     = new Dictionary <DateTime, int>();
            Dictionary <DateTime, double> distanceByDay = new Dictionary <DateTime, double>();

            int CurrentIndex = 0;


            if (journeyRepository.GetChartingDataSet(SelectedTripId, out time, out distance, out timeByDay, out distanceByDay))
            {
                DateTime lowestTimeDay  = timeByDay.Keys.Min();
                DateTime highestTimeDay = timeByDay.Keys.Max();


                DateTime tempDate = lowestTimeDay;
                while (tempDate < highestTimeDay)
                {
                    if (!timeByDay.ContainsKey(tempDate.Date))
                    {
                        timeByDay.Add(tempDate.Date, 0);
                    }

                    tempDate = tempDate.AddDays(1);
                }


                var sortedList = timeByDay.OrderBy(f => f.Key).ToList();
                timeByDay = new Dictionary <DateTime, int>();
                foreach (var k in sortedList)
                {
                    timeByDay.Add(k.Key, k.Value);
                }


                lowestTimeDay  = distanceByDay.Keys.Min();
                highestTimeDay = distanceByDay.Keys.Max();


                tempDate = lowestTimeDay;
                while (tempDate < highestTimeDay)
                {
                    if (!distanceByDay.ContainsKey(tempDate.Date))
                    {
                        distanceByDay.Add(tempDate.Date, 0);
                    }

                    tempDate = tempDate.AddDays(1);
                }

                var sortedList2 = distanceByDay.OrderBy(f => f.Key).ToList();
                distanceByDay = new Dictionary <DateTime, double>();
                foreach (var k in sortedList2)
                {
                    distanceByDay.Add(k.Key, k.Value);
                }



                foreach (KeyValuePair <string, double> distancePairs in distance)
                {
                    Entry entry = new Entry((float)distancePairs.Value)
                    {
                        Color      = SKColor.Parse(GetAColor(CurrentIndex)),
                        Label      = distancePairs.Key,
                        ValueLabel = distancePairs.Value + " miles"
                    };

                    _distanceEntries.Add(entry);
                    CurrentIndex++;
                }
            }


            CurrentIndex = 0;


            foreach (KeyValuePair <string, int> timePairs in time)
            {
                TimeSpan timeLabelSpan = new TimeSpan(0, timePairs.Value, 0);
                string   timeLabel     = timeLabelSpan.ToString(@"hh\:mm");


                Entry entry = new Entry(timePairs.Value)
                {
                    Color      = SKColor.Parse(GetAColor(CurrentIndex)),
                    Label      = timePairs.Key,
                    ValueLabel = timeLabel
                };

                _timeEntries.Add(entry);
                CurrentIndex++;
            }


            foreach (KeyValuePair <DateTime, int> timeByDayPairs in timeByDay)
            {
                TimeSpan timeLabelSpan = new TimeSpan(0, timeByDayPairs.Value, 0);
                string   timeLabel     = timeLabelSpan.ToString(@"hh\:mm");


                Entry entry = new Entry(timeByDayPairs.Value)
                {
                    Color      = SKColor.Parse(GetAColor(0)),
                    Label      = timeByDayPairs.Key.ToShortDateString(),
                    ValueLabel = timeLabel
                };

                _timeByDayEntries.Add(entry);
            }


            foreach (KeyValuePair <DateTime, double> distancePairs in distanceByDay)
            {
                Entry entry = new Entry((float)distancePairs.Value)
                {
                    Color      = SKColor.Parse(GetAColor(0)),
                    Label      = distancePairs.Key.ToShortDateString(),
                    ValueLabel = distancePairs.Value + " miles"
                };

                _distanceByDayEntries.Add(entry);
            }
        }
Beispiel #13
0
        public InfoScreen2()
        {
            InitializeComponent();
            var entries = new[]
            {
                new Entry(30)
                {
                    Label      = "2019-11-07 00:53:51",
                    ValueLabel = "30°C",
                    Color      = SKColor.Parse("#2c3e50")
                },
                new Entry(25)
                {
                    Label      = "2019-11-07 00:57:51",
                    ValueLabel = "25°C",
                    Color      = SKColor.Parse("#77d065")
                },
                new Entry(20)
                {
                    Label      = "2019-11-07 01:01:51",
                    ValueLabel = "20°C",
                    Color      = SKColor.Parse("#b455b6")
                },
                new Entry(24)
                {
                    Label      = "2019-11-07 01:05:51",
                    ValueLabel = "24°C",
                    Color      = SKColor.Parse("#3498db"), TextColor = SKColor.Parse("#b455b6")
                }
            };

            var entries2 = new[]
            {
                new Entry(30)
                {
                    Label      = "2019-11-07 00:53:51",
                    ValueLabel = "30%",
                    Color      = SKColor.Parse("#2c3e50")
                },
                new Entry(27)
                {
                    Label      = "2019-11-07 00:57:51",
                    ValueLabel = "27%",
                    Color      = SKColor.Parse("#77d065")
                },
                new Entry(30)
                {
                    Label      = "2019-11-07 01:01:51",
                    ValueLabel = "30%",
                    Color      = SKColor.Parse("#b455b6")
                },
                new Entry(20)
                {
                    Label      = "2019-11-07 01:05:51",
                    ValueLabel = "20%",
                    Color      = SKColor.Parse("#3498db"), TextColor = SKColor.Parse("#b455b6")
                }
            };

            var entries3 = new[]
            {
                new Entry(700)
                {
                    Label      = "2019-11-07 00:53:51",
                    ValueLabel = "700Lux",
                    Color      = SKColor.Parse("#2c3e50")
                },
                new Entry(900)
                {
                    Label      = "2019-11-07 00:57:51",
                    ValueLabel = "900Lux",
                    Color      = SKColor.Parse("#77d065")
                },
                new Entry(1000)
                {
                    Label      = "2019-11-07 01:01:51",
                    ValueLabel = "1000Lux",
                    Color      = SKColor.Parse("#b455b6")
                },
                new Entry(850)
                {
                    Label      = "2019-11-07 01:05:51",
                    ValueLabel = "850Lux",
                    Color      = SKColor.Parse("#3498db"), TextColor = SKColor.Parse("#b455b6")
                }
            };



            var chart = new LineChart()
            {
                Entries = entries, LabelTextSize = 25, LineMode = LineMode.Straight, LineSize = 8, PointMode = PointMode.Square, PointSize = 18
            };

            this.chartView.Chart = chart;

            var chart1 = new BarChart()
            {
                Entries = entries2, LabelTextSize = 25
            };

            this.chartView1.Chart = chart1;

            var chart2 = new RadialGaugeChart()
            {
                Entries = entries3, LabelTextSize = 25
            };

            this.chartView2.Chart = chart2;
        }
Beispiel #14
0
        /// <inheritdoc/>
        public string EncodeImage(string inputPath, DateTime dateModified, string outputPath, bool autoOrient, ImageOrientation?orientation, int quality, ImageProcessingOptions options, ImageFormat selectedOutputFormat)
        {
            if (string.IsNullOrWhiteSpace(inputPath))
            {
                throw new ArgumentNullException(nameof(inputPath));
            }

            if (string.IsNullOrWhiteSpace(inputPath))
            {
                throw new ArgumentNullException(nameof(outputPath));
            }

            var skiaOutputFormat = GetImageFormat(selectedOutputFormat);

            var hasBackgroundColor = !string.IsNullOrWhiteSpace(options.BackgroundColor);
            var hasForegroundColor = !string.IsNullOrWhiteSpace(options.ForegroundLayer);
            var blur         = options.Blur ?? 0;
            var hasIndicator = options.AddPlayedIndicator || options.UnplayedCount.HasValue || !options.PercentPlayed.Equals(0);

            using (var bitmap = GetBitmap(inputPath, options.CropWhiteSpace, autoOrient, orientation))
            {
                if (bitmap == null)
                {
                    throw new ArgumentOutOfRangeException($"Skia unable to read image {inputPath}");
                }

                var originalImageSize = new ImageDimensions(bitmap.Width, bitmap.Height);

                if (!options.CropWhiteSpace &&
                    options.HasDefaultOptions(inputPath, originalImageSize) &&
                    !autoOrient)
                {
                    // Just spit out the original file if all the options are default
                    return(inputPath);
                }

                var newImageSize = ImageHelper.GetNewImageSize(options, originalImageSize);

                var width  = newImageSize.Width;
                var height = newImageSize.Height;

                using (var resizedBitmap = new SKBitmap(width, height, bitmap.ColorType, bitmap.AlphaType))
                {
                    // scale image
                    bitmap.ScalePixels(resizedBitmap, SKFilterQuality.High);

                    // If all we're doing is resizing then we can stop now
                    if (!hasBackgroundColor && !hasForegroundColor && blur == 0 && !hasIndicator)
                    {
                        Directory.CreateDirectory(Path.GetDirectoryName(outputPath));
                        using (var outputStream = new SKFileWStream(outputPath))
                            using (var pixmap = new SKPixmap(new SKImageInfo(width, height), resizedBitmap.GetPixels()))
                            {
                                pixmap.Encode(outputStream, skiaOutputFormat, quality);
                                return(outputPath);
                            }
                    }

                    // create bitmap to use for canvas drawing used to draw into bitmap
                    using (var saveBitmap = new SKBitmap(width, height)) // , bitmap.ColorType, bitmap.AlphaType))
                        using (var canvas = new SKCanvas(saveBitmap))
                        {
                            // set background color if present
                            if (hasBackgroundColor)
                            {
                                canvas.Clear(SKColor.Parse(options.BackgroundColor));
                            }

                            // Add blur if option is present
                            if (blur > 0)
                            {
                                // create image from resized bitmap to apply blur
                                using (var paint = new SKPaint())
                                    using (var filter = SKImageFilter.CreateBlur(blur, blur))
                                    {
                                        paint.ImageFilter = filter;
                                        canvas.DrawBitmap(resizedBitmap, SKRect.Create(width, height), paint);
                                    }
                            }
                            else
                            {
                                // draw resized bitmap onto canvas
                                canvas.DrawBitmap(resizedBitmap, SKRect.Create(width, height));
                            }

                            // If foreground layer present then draw
                            if (hasForegroundColor)
                            {
                                if (!double.TryParse(options.ForegroundLayer, out double opacity))
                                {
                                    opacity = .4;
                                }

                                canvas.DrawColor(new SKColor(0, 0, 0, (byte)((1 - opacity) * 0xFF)), SKBlendMode.SrcOver);
                            }

                            if (hasIndicator)
                            {
                                DrawIndicator(canvas, width, height, options);
                            }

                            Directory.CreateDirectory(Path.GetDirectoryName(outputPath));
                            using (var outputStream = new SKFileWStream(outputPath))
                            {
                                using (var pixmap = new SKPixmap(new SKImageInfo(width, height), saveBitmap.GetPixels()))
                                {
                                    pixmap.Encode(outputStream, skiaOutputFormat, quality);
                                }
                            }
                        }
                }
            }

            return(outputPath);
        }
Beispiel #15
0
        protected override void OnBackgroundPaint(object sender, SKPaintSurfaceEventArgs e)
        {
            var canvas = e.Surface.Canvas;
            var bound  = e.Info.Rect;

            canvas.Clear();
            var bgColor     = Element.BackgroundColor == Color.Default ? s_defaultColor : SKColor.Parse(Element.BackgroundColor.ToHex());
            var borderColor = Element.BorderColor == Color.Default ? s_defaultColor : SKColor.Parse(Element.BorderColor.ToHex());
            var roundRect   = CreateRoundRect(bound);

            using (var paint = new SKPaint
            {
                IsAntialias = true,
            })
            {
                if (Element.HasShadow)
                {
                    paint.Color = SKColors.White;
                    paint.Style = SKPaintStyle.Stroke;
                    // Draw shadow
                    paint.ImageFilter = SKImageFilter.CreateDropShadowOnly(
                        Forms.ConvertToScaledPixel(0),
                        Forms.ConvertToScaledPixel(0),
                        Forms.ConvertToScaledPixel(s_borderWidth * 2),
                        Forms.ConvertToScaledPixel(s_borderWidth * 2),
                        SKColors.Black);
                    canvas.DrawRoundRect(roundRect, paint);
                }

                paint.ImageFilter = null;
                paint.Style       = SKPaintStyle.Fill;
                paint.Color       = bgColor;

                // Draw background color
                canvas.DrawRoundRect(roundRect, paint);

                paint.Style       = SKPaintStyle.Stroke;
                paint.StrokeWidth = Forms.ConvertToScaledPixel(s_borderWidth);
                paint.Color       = borderColor;

                // Draw Background (Brush)
                using (var brushPaint = Element.GetBackgroundPaint(bound))
                {
                    if (brushPaint != null)
                    {
                        canvas.DrawRoundRect(roundRect, brushPaint);
                    }
                }

                // Draw border
                canvas.DrawRoundRect(roundRect, paint);
            }
        }
Beispiel #16
0
        /// <summary>
        /// Отрисовывает график по месяцам
        /// </summary>
        /// <returns></returns>
        static public bool FillMonthGraph()
        {
            //Лист с точками на графике
            List <Entry> entries = new List <Entry>();

            try
            {
                //Чтение файла
                using (StreamReader reader = new StreamReader(filename))
                {
                    string json = reader.ReadToEnd();
                    dayStats = JsonConvert.DeserializeObject <List <DayStat> >(json);
                }

                List <Classes_For_Stats.MonthStat> monthStats = new List <Classes_For_Stats.MonthStat>();

                List <DayStat> days      = new List <DayStat>();
                int            tempMonth = dayStats[0].Date.Month;

                //По дням создаются объекты MonthStat
                for (int i = 0; i < dayStats.Count - 1; i++)
                {
                    days.Add(dayStats[i]);

                    //Если день уже принадлежит другому месяцу, то создает новый MonthStat объект
                    if (dayStats[i + 1].Date.Month != tempMonth)
                    {
                        monthStats.Add(new Classes_For_Stats.MonthStat(days, namesOfMonths[dayStats[i].Date.Month]));
                        days = null;
                    }
                }

                if (days != null)
                {
                    monthStats.Add(new Classes_For_Stats.MonthStat(days, namesOfMonths[days[0].Date.Month]));
                }

                //Создание точек
                foreach (Classes_For_Stats.MonthStat week in monthStats)
                {
                    entries.Add(new Entry(week.PagesTotal)
                    {
                        Color      = SKColor.Parse("#4285F4"),
                        Label      = week.Month,
                        ValueLabel = week.PagesTotal.ToString(),
                    });
                }

                //Настройка графика
                StatsOfReadingByDates.HeightRequest     = 500;
                StatsOfReadingByDates.WidthRequest      = 100 * entries.Count;
                StatsOfReadingByDates.HorizontalOptions = LayoutOptions.End;
                StatsOfReadingByDates.VerticalOptions   = LayoutOptions.End;
                StatsOfReadingByDates.Chart             = new Microcharts.LineChart {
                    Entries = entries, LabelTextSize = 40, BackgroundColor = SKColor.Parse("#FAFAFA")
                };
                //После успешного чтения возращает true
                return(true);
            }
            catch (Exception ex)
            {
                //Если ловится исключение, то возвращает false
                return(false);
            }
        }
Beispiel #17
0
 private SKColor GetRandomColor()
 {
     return(SKColor.Parse(GraphicsUtil.HexConverter()));
 }
Beispiel #18
0
        private Stream Draw()
        {
            string chars     = null;
            string upperData = null;

            if (string.IsNullOrEmpty(_data))
            {
                chars = "..";
            }
            else if (_data?.Length > 1)
            {
                upperData = _data.ToUpper();
                chars     = GetFirstLetters(upperData, 2);
            }
            else
            {
                chars = upperData = _data.ToUpper();
            }

            var bgColor   = StringToColor(upperData);
            var textColor = Color.White;
            var size      = 50;

            var bitmap = new SKBitmap(
                size * 2,
                size * 2,
                SKImageInfo.PlatformColorType,
                SKAlphaType.Premul);
            var canvas = new SKCanvas(bitmap);

            canvas.Clear(SKColors.Transparent);

            var midX   = canvas.LocalClipBounds.Size.ToSizeI().Width / 2;
            var midY   = canvas.LocalClipBounds.Size.ToSizeI().Height / 2;
            var radius = midX - midX / 5;

            var circlePaint = new SKPaint
            {
                IsAntialias = true,
                Style       = SKPaintStyle.Fill,
                StrokeJoin  = SKStrokeJoin.Miter,
                Color       = SKColor.Parse(bgColor.ToHex())
            };

            canvas.DrawCircle(midX, midY, radius, circlePaint);

            var typeface  = SKTypeface.FromFamilyName("Arial", SKFontStyle.Normal);
            var textSize  = midX / 1.3f;
            var textPaint = new SKPaint
            {
                IsAntialias = true,
                Style       = SKPaintStyle.Fill,
                Color       = SKColor.Parse(textColor.ToHex()),
                TextSize    = textSize,
                TextAlign   = SKTextAlign.Center,
                Typeface    = typeface
            };
            var rect = new SKRect();

            textPaint.MeasureText(chars, ref rect);
            canvas.DrawText(chars, midX, midY + rect.Height / 2, textPaint);

            return(SKImage.FromBitmap(bitmap).Encode(SKEncodedImageFormat.Png, 100).AsStream());
        }
Beispiel #19
0
        public void GetDate()
        {
            var   realm               = Realm.GetInstance();
            var   eat                 = realm.All <CurrentExpense>();
            float eatSum              = 0;
            float FunSum              = 0;
            float publicTrunsportSum  = 0;
            float privatetransportSum = 0;
            float homePeatSum         = 0;
            float clothingSum         = 0;
            float medicineSum         = 0;
            float residenceSum        = 0;
            float otherSum            = 0;

            float chekEntryes = 0;

            foreach (var s in eat)
            {
                if (s.Expense.ExpenseName == "Їжа")
                {
                    eatSum += float.Parse(s.ExpenseSum.ToString());
                }
                else if (s.Expense.ExpenseName == "Розваги")
                {
                    FunSum += float.Parse(s.ExpenseSum.ToString());
                }
                else if (s.Expense.ExpenseName == "Громадський транспорт")
                {
                    publicTrunsportSum += float.Parse(s.ExpenseSum.ToString());
                }
                else if (s.Expense.ExpenseName == "Особистий транспорт")
                {
                    privatetransportSum += float.Parse(s.ExpenseSum.ToString());
                }
                else if (s.Expense.ExpenseName == "Домашній улюбленець")
                {
                    homePeatSum += float.Parse(s.ExpenseSum.ToString());
                }
                else if (s.Expense.ExpenseName == "Одяг")
                {
                    clothingSum += float.Parse(s.ExpenseSum.ToString());
                }
                else if (s.Expense.ExpenseName == "Медицина")
                {
                    medicineSum += float.Parse(s.ExpenseSum.ToString());
                }
                else if (s.Expense.ExpenseName == "Проживання")
                {
                    residenceSum += float.Parse(s.ExpenseSum.ToString());
                }
                else if (s.Expense.ExpenseName == "Інше")
                {
                    otherSum += float.Parse(s.ExpenseSum.ToString());
                }
            }

            entries = new List <Entry>()
            {
                new Entry(eatSum)
                {
                    Label      = "Їжа",
                    ValueLabel = eatSum.ToString(),
                    Color      = SKColor.Parse("#ff001e")
                },

                new Entry(FunSum)
                {
                    Label      = "Розваги",
                    ValueLabel = FunSum.ToString(),
                    Color      = SKColor.Parse("#ffa200")
                },

                new Entry(publicTrunsportSum)
                {
                    Label      = "Громадський транспорт",
                    ValueLabel = publicTrunsportSum.ToString(),
                    Color      = SKColor.Parse("#0088ff")
                },

                new Entry(privatetransportSum)
                {
                    Label      = "Особистий транспорт",
                    ValueLabel = privatetransportSum.ToString(),
                    Color      = SKColor.Parse("#00ff00")
                },

                new Entry(homePeatSum)
                {
                    Label      = "Домашній улюбленець",
                    ValueLabel = homePeatSum.ToString(),
                    Color      = SKColor.Parse("#00fbff")
                },

                new Entry(clothingSum)
                {
                    Label      = "Одяг",
                    ValueLabel = clothingSum.ToString(),
                    Color      = SKColor.Parse("#002aff")
                },

                new Entry(medicineSum)
                {
                    Label      = "Медицина",
                    ValueLabel = medicineSum.ToString(),
                    Color      = SKColor.Parse("#d000ff")
                },

                new Entry(residenceSum)
                {
                    Label      = "Проживання",
                    ValueLabel = residenceSum.ToString(),
                    Color      = SKColor.Parse("#ff0090")
                },

                new Entry(otherSum)
                {
                    Label      = "Інше",
                    ValueLabel = otherSum.ToString(),
                    Color      = SKColor.Parse("#0099ff")
                },
            };

            int          tempIterator = 0;
            List <Entry> tempEntries  = new List <Entry>();

            foreach (var e in entries)
            {
                if (e.Value != chekEntryes)
                {
                    tempEntries.Add(e);
                }
                tempIterator++;
            }

            entries = tempEntries;
        }
Beispiel #20
0
        public byte[] DrawAreaAtSize(ImageStats stats, List <CompletePaintOp> paintOps)
        {
            //This is the new core drawing function. Once the paint operations have been created, I just draw them here.
            //baseline image data stuff
            SKBitmap bitmap = new SKBitmap(stats.imageSizeX, stats.imageSizeY, SKColorType.Rgba8888, SKAlphaType.Premul);
            SKCanvas canvas = new SKCanvas(bitmap);

            canvas.Clear(eraser.Color);
            canvas.Scale(1, -1, stats.imageSizeX / 2, stats.imageSizeY / 2);
            SKPaint paint = new SKPaint();

            foreach (var w in paintOps.OrderByDescending(p => p.paintOp.LayerId).ThenByDescending(p => p.areaSize))
            {
                paint = cachedPaints[w.paintOp.Id]; //SetPaintForTPP(w.paintOp); // w.paintOp.paint;

                if (w.paintOp.FromTag)              //FromTag is for when you are saving color data directly to each element, instead of tying it to a styleset.
                {
                    paint.Color = SKColor.Parse(w.tagValue);
                }

                if (w.paintOp.Randomize) //To randomize the color on every Draw call.
                {
                    paint.Color = new SKColor((byte)r.Next(0, 255), (byte)r.Next(0, 255), (byte)r.Next(0, 255), 99);
                }

                paint.StrokeWidth = (float)w.lineWidthPixels;
                var path = new SKPath();
                switch (w.elementGeometry.GeometryType)
                {
                case "Polygon":
                    var p = w.elementGeometry as Polygon;
                    //if (p.Envelope.Length < (stats.degreesPerPixelX * 4)) //This poly's perimeter is too small to draw
                    //continue;
                    path.AddPoly(PolygonToSKPoints(p.ExteriorRing, stats.area, stats.degreesPerPixelX, stats.degreesPerPixelY));
                    foreach (var ir in p.Holes)
                    {
                        //if (ir.Envelope.Length < (w.lineWidth * 4)) //This poly's perimeter is less than 2x2 pixels in size.
                        //continue;
                        path.AddPoly(PolygonToSKPoints(ir, stats.area, stats.degreesPerPixelX, stats.degreesPerPixelY));
                    }
                    canvas.DrawPath(path, paint);
                    break;

                case "MultiPolygon":
                    foreach (var p2 in ((MultiPolygon)w.elementGeometry).Geometries)
                    {
                        //if (p2.Envelope.Length < (stats.degreesPerPixelX * 4)) //This poly's perimeter is too small to draw
                        //continue;
                        var p2p = p2 as Polygon;
                        path.AddPoly(PolygonToSKPoints(p2p.ExteriorRing, stats.area, stats.degreesPerPixelX, stats.degreesPerPixelY));
                        foreach (var ir in p2p.Holes)
                        {
                            //if (ir.Envelope.Length < (stats.degreesPerPixelX * 4)) //This poly's perimeter is too small to draw
                            // continue;
                            path.AddPoly(PolygonToSKPoints(ir, stats.area, stats.degreesPerPixelX, stats.degreesPerPixelY));
                        }
                        canvas.DrawPath(path, paint);
                    }
                    break;

                case "LineString":
                    var firstPoint = w.elementGeometry.Coordinates.First();
                    var lastPoint  = w.elementGeometry.Coordinates.Last();
                    var points     = PolygonToSKPoints(w.elementGeometry, stats.area, stats.degreesPerPixelX, stats.degreesPerPixelY);
                    if (firstPoint.Equals(lastPoint))
                    {
                        //This is a closed shape. Check to see if it's supposed to be filled in.
                        if (paint.Style == SKPaintStyle.Fill)
                        {
                            path.AddPoly(points);
                            canvas.DrawPath(path, paint);
                            continue;
                        }
                    }
                    //if (w.lineWidth < 1) //Don't draw lines we can't see.
                    //continue;
                    for (var line = 0; line < points.Length - 1; line++)
                    {
                        canvas.DrawLine(points[line], points[line + 1], paint);
                    }
                    break;

                case "MultiLineString":
                    //if (w.lineWidth < 1) //Don't draw lines we can't see.
                    //continue;
                    foreach (var p3 in ((MultiLineString)w.elementGeometry).Geometries)
                    {
                        var points2 = PolygonToSKPoints(p3, stats.area, stats.degreesPerPixelX, stats.degreesPerPixelY);
                        for (var line = 0; line < points2.Length - 1; line++)
                        {
                            canvas.DrawLine(points2[line], points2[line + 1], paint);
                        }
                    }
                    break;

                case "Point":
                    var convertedPoint = PolygonToSKPoints(w.elementGeometry, stats.area, stats.degreesPerPixelX, stats.degreesPerPixelY);
                    //If this type has an icon, use it. Otherwise draw a circle in that type's color.
                    if (!string.IsNullOrEmpty(w.paintOp.FileName))
                    {
                        SKBitmap icon = SKBitmap.Decode(TagParser.cachedBitmaps[w.paintOp.FileName]);     //TODO optimize by making icons in Initialize.
                        canvas.DrawBitmap(icon, convertedPoint[0]);
                    }
                    else
                    {
                        var circleRadius = (float)(ConstantValues.resolutionCell10 / stats.degreesPerPixelX / 2);     //I want points to be drawn as 1 Cell10 in diameter.
                        canvas.DrawCircle(convertedPoint[0], circleRadius, paint);
                        //TODO re-add outline paint to this DLL not TagParser.
                        //canvas.DrawCircle(convertedPoint[0], circleRadius, TagParser.outlinePaint);
                    }
                    break;

                default:
                    Log.WriteLog("Unknown geometry type found, not drawn.");
                    break;
                }
            }
            //}

            var ms   = new MemoryStream();
            var skms = new SKManagedWStream(ms);

            bitmap.Encode(skms, SKEncodedImageFormat.Png, 100);
            var results = ms.ToArray();

            skms.Dispose(); ms.Close(); ms.Dispose();
            return(results);
        }
        protected override bool OnDraw(SciterElement se, DrawArgs args)
        {
            if (args.DrawEvent == _drawEvent)
            {
                using (SKBitmap bitmap = new SKBitmap(width: args.Area.Width, height: args.Area.Height, colorType: SKColorType.Rgba8888, alphaType: SKAlphaType.Premul))
                    using (SKCanvas canvas = new SKCanvas(bitmap))
                        using (SKPaint paint = new SKPaint())
                        {
                            paint.IsAntialias = true;
                            canvas.Clear();

                            paint.Shader = SKShader.CreateRadialGradient(
                                new SKPoint(args.Area.Width / 2f, args.Area.Height / 2f),
                                Math.Max(args.Area.Width, args.Area.Height) / 10f,
                                new SKColor[] { SKColor.Parse("#77FFFFFF"), SKColor.Parse("#33FFFFFF"), SKColor.Parse("#00000000") },
                                null,
                                SKShaderTileMode.Mirror);

                            canvas.DrawRect(new SKRect(0, 0, args.Area.Width, args.Area.Height), paint);

                            var img = bitmap.ToSciterImage();
                            var gfx = SciterGraphics.Create(args.Handle);
                            gfx.BlendImage(img, args.Area.Left, args.Area.Top);

                            //return true;
                        }
            }

            return(base.OnDraw(se, args));
        }
Beispiel #22
0
        /// <summary>
        /// Creates an SVG image instead of a PNG file, but otherwise operates the same as DrawAreaAtSize.
        /// </summary>
        /// <param name="stats">the image properties to draw</param>
        /// <param name="drawnItems">the list of elements to draw. Will load from the database if null.</param>
        /// <param name="styles">a dictionary of TagParserEntries to select to draw</param>
        /// <param name="filterSmallAreas">if true, skips entries below a certain size when drawing.</param>
        /// <returns>a string containing the SVG XML</returns>
        public string DrawAreaAtSizeSVG(ImageStats stats, List <DbTables.Place> drawnItems = null, Dictionary <string, StyleEntry> styles = null, bool filterSmallAreas = true)
        {
            //TODO: make this take CompletePaintOps
            //This is the new core drawing function. Takes in an area, the items to draw, and the size of the image to draw.
            //The drawn items get their paint pulled from the TagParser's list. If I need multiple match lists, I'll need to make a way
            //to pick which list of tagparser rules to use.

            if (styles == null)
            {
                styles = TagParser.allStyleGroups.First().Value;
            }

            double minimumSize = 0;

            if (filterSmallAreas)
            {
                minimumSize = stats.degreesPerPixelX; //don't draw elements under 1 pixel in size. at slippy zoom 12, this is approx. 1 pixel for a Cell10.
            }
            var db  = new PraxisContext();
            var geo = Converters.GeoAreaToPolygon(stats.area);

            if (drawnItems == null)
            {
                drawnItems = GetPlaces(stats.area, filterSize: minimumSize);
            }

            //baseline image data stuff
            //SKBitmap bitmap = new SKBitmap(stats.imageSizeX, stats.imageSizeY, SKColorType.Rgba8888, SKAlphaType.Premul);
            var          bounds = new SKRect(0, 0, stats.imageSizeX, stats.imageSizeY);
            MemoryStream s      = new MemoryStream();
            SKCanvas     canvas = SKSvgCanvas.Create(bounds, s); //output not guaranteed to be complete until the canvas is deleted?!?
            //SKCanvas canvas = new SKCanvas(bitmap);
            var bgColor = SKColor.Parse(styles["background"].PaintOperations.First().HtmlColorCode);

            //Backgound is a named style, unmatched will be the last entry and transparent.
            canvas.Clear(bgColor);
            canvas.Scale(1, -1, stats.imageSizeX / 2, stats.imageSizeY / 2);
            SKPaint paint = new SKPaint();

            //I guess what I want here is a list of an object with an elementGeometry object for the shape, and a paintOp attached to it
            var pass1 = drawnItems.Select(d => new { d.AreaSize, d.ElementGeometry, paintOp = styles[d.GameElementName].PaintOperations });
            var pass2 = new List <CompletePaintOp>(drawnItems.Count() * 2);

            foreach (var op in pass1)
            {
                foreach (var po in op.paintOp)
                {
                    pass2.Add(new CompletePaintOp(op.ElementGeometry, op.AreaSize, po, "", po.LineWidthDegrees * stats.pixelsPerDegreeX));
                }
            }


            foreach (var w in pass2.OrderByDescending(p => p.paintOp.LayerId).ThenByDescending(p => p.areaSize))
            {
                paint = cachedPaints[w.paintOp.Id];
                if (paint.Color.Alpha == 0)
                {
                    continue; //This area is transparent, skip drawing it entirely.
                }
                if (stats.degreesPerPixelX > w.paintOp.MaxDrawRes || stats.degreesPerPixelX < w.paintOp.MinDrawRes)
                {
                    continue; //This area isn't drawn at this scale.
                }
                var path = new SKPath();
                switch (w.elementGeometry.GeometryType)
                {
                //Polygons without holes are super easy and fast: draw the path.
                //Polygons with holes require their own bitmap to be drawn correctly and then overlaid onto the canvas.
                //I want to use paths to fix things for performance reasons, but I have to use Bitmaps because paths apply their blend mode to
                //ALL elements already drawn, not just the last one.
                case "Polygon":
                    var p = w.elementGeometry as Polygon;

                    path.AddPoly(PolygonToSKPoints(p, stats.area, stats.degreesPerPixelX, stats.degreesPerPixelY));
                    foreach (var hole in p.InteriorRings)
                    {
                        path.AddPoly(PolygonToSKPoints(hole, stats.area, stats.degreesPerPixelX, stats.degreesPerPixelY));
                    }
                    canvas.DrawPath(path, paint);

                    break;

                case "MultiPolygon":
                    foreach (var p2 in ((MultiPolygon)w.elementGeometry).Geometries)
                    {
                        var p2p = p2 as Polygon;
                        path.AddPoly(PolygonToSKPoints(p2p, stats.area, stats.degreesPerPixelX, stats.degreesPerPixelY));
                        foreach (var hole in p2p.InteriorRings)
                        {
                            path.AddPoly(PolygonToSKPoints(hole, stats.area, stats.degreesPerPixelX, stats.degreesPerPixelY));
                        }
                        canvas.DrawPath(path, paint);
                    }
                    break;

                case "LineString":
                    var firstPoint = w.elementGeometry.Coordinates.First();
                    var lastPoint  = w.elementGeometry.Coordinates.Last();
                    var points     = PolygonToSKPoints(w.elementGeometry, stats.area, stats.degreesPerPixelX, stats.degreesPerPixelY);
                    if (firstPoint.Equals(lastPoint))
                    {
                        //This is a closed shape. Check to see if it's supposed to be filled in.
                        if (paint.Style == SKPaintStyle.Fill)
                        {
                            path.AddPoly(points);
                            canvas.DrawPath(path, paint);
                            continue;
                        }
                    }
                    for (var line = 0; line < points.Length - 1; line++)
                    {
                        canvas.DrawLine(points[line], points[line + 1], paint);
                    }
                    break;

                case "MultiLineString":
                    foreach (var p3 in ((MultiLineString)w.elementGeometry).Geometries)
                    {
                        var points2 = PolygonToSKPoints(p3, stats.area, stats.degreesPerPixelX, stats.degreesPerPixelY);
                        for (var line = 0; line < points2.Length - 1; line++)
                        {
                            canvas.DrawLine(points2[line], points2[line + 1], paint);
                        }
                    }
                    break;

                case "Point":
                    var convertedPoint = PolygonToSKPoints(w.elementGeometry, stats.area, stats.degreesPerPixelX, stats.degreesPerPixelY);
                    //If this type has an icon, use it. Otherwise draw a circle in that type's color.
                    if (!string.IsNullOrEmpty(w.paintOp.FileName))
                    {
                        SKBitmap icon = SKBitmap.Decode(TagParser.cachedBitmaps[w.paintOp.FileName]);     //TODO optimize by creating in Initialize
                        canvas.DrawBitmap(icon, convertedPoint[0]);
                    }
                    else
                    {
                        var circleRadius = (float)(ConstantValues.resolutionCell10 / stats.degreesPerPixelX / 2);     //I want points to be drawn as 1 Cell10 in diameter.
                        canvas.DrawCircle(convertedPoint[0], circleRadius, paint);
                    }
                    break;

                default:
                    Log.WriteLog("Unknown geometry type found, not drawn.");
                    break;
                }
            }
            canvas.Flush();
            canvas.Dispose();
            canvas     = null;
            s.Position = 0;
            var svgData = new StreamReader(s).ReadToEnd();

            return(svgData);
        }
Beispiel #23
0
        private void picker2_SelectedIndexChanged(object sender, EventArgs e)
        {
            stackLayout3.Children.Clear();
            stackLayout4.Children.Clear();

            if (picker2.SelectedIndex == 0)
            {
                CreateSpentChart();
            }
            else if (picker2.SelectedIndex == 1)
            {
                int          CntMoneyAll = 0;
                List <Entry> entries     = new List <Entry>();

                DateTime dateTimeNow = DateTime.Today;
                DateTime dateTimeLast;
                int      Spent;

                for (int i = 0; i < 12; ++i)
                {
                    Spent = 0;
                    bool Check = false;
                    dateTimeLast = new DateTime(dateTimeNow.Year, dateTimeNow.Month, dateTimeNow.Day);

                    var config = new RealmConfiguration()
                    {
                        SchemaVersion = 1
                    };
                    Realm _realm = Realm.GetInstance(config);

                    while (dateTimeNow.Month == dateTimeLast.Month)
                    {
                        string nowdate = (new MyDate(dateTimeNow)).ToString();
                        var    NowDays = _realm.All <Day>().Where(f => f.Date == nowdate).ToList();
                        if (NowDays.Count == 0)
                        {
                            break;
                        }
                        var NowDay = NowDays[0];

                        Spent += NowDay.SpentOnSigaretToday;

                        dateTimeLast = new DateTime(dateTimeNow.Year, dateTimeNow.Month, dateTimeNow.Day);
                        dateTimeNow  = dateTimeNow.AddDays(-1);
                        Check        = true;
                    }

                    if (Check)
                    {
                        CntMoneyAll += Spent;
                        entries.Add(new Entry(Spent)
                        {
                            ValueLabel = Spent.ToString(),
                            Label      = ParseToMonth[dateTimeLast.Month - 1],
                            Color      = SKColor.Parse("#FF6E40")
                        });
                    }
                    else
                    {
                        break;
                    }
                }

                LabelCntMoney.Text = "Потрачено денег за указанный период: " + CntMoneyAll + "RUB";
                entries.Reverse();
                SpentChart.Chart = new BarChart {
                    Entries = entries, LabelTextSize = (float)Device.GetNamedSize(NamedSize.Small, typeof(Label))
                };
            }
            else
            {
                StartPeriod2 = new Label()
                {
                    Text            = "Начало периода: ",
                    TextColor       = Color.FromHex("FFC4C4C4"),
                    VerticalOptions = LayoutOptions.CenterAndExpand
                };
                stackLayout3.Children.Add(StartPeriod2);
                EndPeriod2 = new Label()
                {
                    Text            = "Конец периода: ",
                    TextColor       = Color.FromHex("FFC4C4C4"),
                    VerticalOptions = LayoutOptions.CenterAndExpand
                };
                stackLayout4.Children.Add(EndPeriod2);

                datePickerFrom2 = new DatePicker()
                {
                    TextColor = Color.FromHex("#FFC4C4C4"), VerticalOptions = LayoutOptions.CenterAndExpand
                };
                datePickerFrom2.DateSelected += WantCreatePeriodSpentChart;
                stackLayout3.Children.Add(datePickerFrom2);

                datePickerTo2 = new DatePicker()
                {
                    TextColor = Color.FromHex("#FFC4C4C4"), VerticalOptions = LayoutOptions.CenterAndExpand
                };
                datePickerTo2.DateSelected += WantCreatePeriodSpentChart;
                stackLayout4.Children.Add(datePickerTo2);

                DateTime From = datePickerFrom2.Date;
                DateTime To   = datePickerTo2.Date;

                if (DateTime.Compare(From, To) > 0)
                {
                    DisplayAlert("", "Начало периода должно быть раньше конца периода!", "OK");
                    return;
                }

                CreatePeriodSpentChart();
            }
        }
Beispiel #24
0
        /// <summary>
        /// Get the background color from a style set
        /// </summary>
        /// <param name="styleSet">the name of the style set to pull the background color from</param>
        /// <returns>the SKColor saved into the requested background paint object.</returns>
        public SKColor GetStyleBgColor(string styleSet)
        {
            var color = SKColor.Parse(TagParser.allStyleGroups[styleSet]["background"].PaintOperations.First().HtmlColorCode);

            return(color);
        }
Beispiel #25
0
        private async Task SetWeather()
        {
            var storagedWeather = await new WeatherController().LocalData.List(new Data.Models.Query.SQLControllerListCriteriaModel
            {
                Filter = new System.Collections.Generic.List <Data.Models.Query.SQLControllerListFilterField>
                {
                    new Data.Models.Query.SQLControllerListFilterField
                    {
                        FieldName   = "Created",
                        ValueLBound = DateTime.Now.Date.ToString(),
                        ValueUBound = DateTime.Now.Date.AddDays(1).AddTicks(-1).ToString(),
                        DateKind    = Data.Models.Query.SQLControllerListFilterField.DateKindEnum.Localized
                    }
                }
            });

            if (storagedWeather.Any())
            {
                Weather = storagedWeather.FirstOrDefault();
            }
            else
            {
                var device = await Utils.GetPositionAsync();

                if (device != null)
                {
                    WeatherHistoryRoot weather = null;
                    try
                    {
                        weather = await DependencyService.Get <IWeatherService>().GetOneCall(device.Latitude, device.Longitude);
                    }
                    catch (Exception e)
                    {
                        Weather = (await new WeatherController().LocalData.List().ConfigureAwait(false)).LastOrDefault();
                    }

                    if (weather != null && Weather == null)
                    {
                        Weather = new WeatherModel
                        {
                            Id          = Guid.Empty,
                            WeatherJson = JsonConvert.SerializeObject(weather)
                        };

                        await new WeatherController().LocalData.Modify(Weather);
                        Weather.RaiseFields();
                    }
                }
            }

            if (Weather != null)
            {
                Temperature = new LineChart
                {
                    Entries = Weather.Main.daily.Select(x => new ChartEntry(x.temp.day)
                    {
                        Label      = CastDtToDayOfWeek(x.dt),
                        ValueLabel = x.temp.day.ToString("f0"),
                        Color      = SKColor.Parse(GetTemperatureColor(x.temp.day))
                    })
                };

                Rain = new LineChart
                {
                    Entries = Weather.Main.daily.Select(x => new ChartEntry(x.rain)
                    {
                        Label      = CastDtToDayOfWeek(x.dt),
                        ValueLabel = x.rain.ToString("f0"),
                        Color      = SKColor.Parse("#2389da")
                    })
                };

                OnPropertyChanged("TempColor");
            }

            await Task.Delay(100);
        }
Beispiel #26
0
        protected override void DrawCaption(SKCanvas canvas, int cx, int cy, float radius, float relativeScaleWidth,
                                            float strokeWidth)
        {
            if (CurrentValueEntry != null)
            {
                canvas.DrawCaptionLabels(string.Empty, SKColor.Empty, $"{CurrentValueEntry.Value}%", SKColor.Parse("#283748"),
                                         LabelTextSize * relativeScaleWidth,
                                         new SKPoint(cx - CaptionMargin, cy / 2f + LabelTextSize), SKTextAlign.Center);
            }

            // uncomment to add Desired value
            //var desiredValue = values.Skip(1).Take(1).FirstOrDefault();
            //canvas.DrawCaptionLabels(string.Empty, SKColor.Empty, $"Desired: {desiredValue?.Value}%", SKColor.Parse("#378D93"), LabelTextSize * relativeScaleWidth,
            //    new SKPoint(cx - CaptionMargin, cy / 2f + 3 * strokeWidth * 1.45f), SKTextAlign.Center);
        }