Пример #1
0
        //STAMPA
        private void canvasView_PaintSurface(object sender, SkiaSharp.Views.Forms.SKPaintSurfaceEventArgs e)
        {
            if (startup)
            {
                translateBottonBarDown();                                         //la barra non c'è
                rocketLabel.TranslateTo(0, -rocketLabelImage.Height * 2, 0);      //il dita del razzo non ci sono
                rocketLabelImage.TranslateTo(0, -rocketLabelImage.Height * 2, 0); //il razzo non c'è
                startup = false;
            }

            SKSurface surface = e.Surface;
            SKCanvas  canvas  = surface.Canvas;

            canvas.Clear();

            //seleziono le liste sincronizzate (terra) o non sincronizzate (tutto il resto)
            if (observer.Equals("earth"))
            {
                tempPlanets        = syncPlanets;
                tempConstellations = syncConstellations;
                tempStars          = syncStars;
                tempPoints         = syncPoints;
            }
            else
            {
                tempPlanets        = planets;
                tempConstellations = constellations;
                tempStars          = stars;
                tempPoints         = points;
            }

            //stampo le stelle
            for (int i = 0; i < tempStars.Count; i++)
            {
                canvas.DrawCircle(toScreen(tempStars[i]), 1, tempStars[i].paint);
            }

            //stampo le costellazioni
            //SI BUGGA SE METTEREMO LO ZOOM, CHIEDI AL PIETRO
            tempConstellations.drawAll(canvas);

            //stampo i punti di riferimento (sud, nord, equatore)
            for (int i = 0; i < tempPoints.Count; i++)
            {
                if (tempPoints[i].name.Equals("NORTHPOLE"))
                {
                    canvas.DrawCircle(toScreen(tempPoints[i]), 60, uselessPaint);
                }
                else if (tempPoints[i].name.Equals("SOUTHPOLE"))
                {
                    canvas.DrawCircle(toScreen(tempPoints[i]), 60, uselessPaint);
                }
                else
                {
                    canvas.DrawCircle(toScreen(tempPoints[i]), 4, uselessPaint);
                }
            }

            /*canvas.DrawCircle(toScreen(new Planet("SOUTHPOLE", 0, -90, 10, new SKColor(255, 255, 255))), 60, uselessPaint);
             * canvas.DrawCircle(toScreen(new Planet("NORTHPOLE", 0, 90, 10, new SKColor(127, 127, 127))), 60, uselessPaint);
             * for (float i = 0; i <= 360; i = i + 0.2f)
             *  canvas.DrawCircle(toScreen(new Planet("EQUATOR", i, 0, 3, new SKColor(0, 127, 127))), 5, uselessPaint);*/

            //stampo i pianeti
            for (int i = 0; i < tempPlanets.Count; i++)
            {
                if (tempPlanets[i].name == observer)  //non stampo la terra o il sole in base dal punto di vista
                {
                    continue;
                }

                SKPoint tempPoint = toScreen(tempPlanets[i]);
                //sposto le coordinate di stampa del pianeta in base alla dimensione con cui viene stampato (drawbitmap non disegna partendo dal centro)
                tempPoint.X -= (200 + tempPlanets[i].printSize * 15) / 2;
                tempPoint.Y -= (200 + tempPlanets[i].printSize * 15) / 2;

                if (theme.Equals("image"))              //disegno i pianeti come immagini stilizzate
                {
                    canvas.DrawBitmap(tempPlanets[i].texture, SKRect.Create(tempPoint, new SKSize(200 + tempPlanets[i].printSize * 15, 200 + tempPlanets[i].printSize * 15)), null);
                }
                else if (theme.Equals("imageHD"))            //disegno i pianeti come immagini reali
                {
                    canvas.DrawBitmap(tempPlanets[i].textureHD, SKRect.Create(tempPoint, new SKSize(200 + tempPlanets[i].printSize * 15, 200 + tempPlanets[i].printSize * 15)), null);
                }
            }
        }
Пример #2
0
 public override void Draw(SKCanvas canvas, SKPoint pos, IChartBase chart)
 {
     new TextLayout().Draw(canvas, text, SKRect.Create(pos.X, pos.Y, 250, 50));
     base.Draw(canvas, pos, chart);
 }
Пример #3
0
        private void onClickRenderBtn(object sender, EventArgs e)
        {
            string xText = xPos.Text,
                   yText = yPos.Text;
            float x, y;

            try
            {
                float.TryParse(xText, out x);
                float.TryParse(yText, out y);

                SKImageInfo imageInfo = new SKImageInfo(300, 250);

                using (SKSurface surface = SKSurface.Create(imageInfo))
                {
                    SKCanvas canvas = surface.Canvas;

                    canvas.Clear(SKColors.Red);

                    //draw Xamagon
                    using (SKPaint paint = new SKPaint())
                    {
                        paint.IsAntialias = true;
                        paint.Color       = new SKColor(0x2c, 0x3e, 0x50);
                        paint.StrokeCap   = SKStrokeCap.Round;

                        //create the path
                        using (SKPath 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);
                        }
                    }

                    using (WebClient client = new WebClient())
                        using (Stream stream = client.OpenRead("https://via.placeholder.com/200x100"))
                        {
                            SKBitmap bitmap = SKBitmap.Decode(stream);
                            canvas.DrawBitmap(bitmap, SKRect.Create(30, 30, 200, 100));
                        }

                    using (SKPaint textPaint = new SKPaint())
                        using (SKTypeface tf = SKTypeface.FromFamilyName("Courier New"))
                        {
                            textPaint.Color       = SKColor.Parse("0000cc");
                            textPaint.IsAntialias = true;
                            textPaint.TextSize    = 24;
                            canvas.DrawText("Test", 30, 30, textPaint); //x and y are baseline
                        }

                    using (SKImage image = surface.Snapshot())
                        using (SKData data = image.Encode(SKEncodedImageFormat.Png, 100))
                            using (MemoryStream mStream = new MemoryStream(data.ToArray()))
                            {
                                Bitmap bm = new Bitmap(mStream, false);
                                skiaImage.Image = bm;
                            }
                }
            }
            catch (Exception ex)
            {
            }
        }
Пример #4
0
        private void DrawData(SKCanvas Canvas)
        {
            IsInvalidData = false;
            var AntialiasPieRadius   = PieRadius - AntialiasMargin;
            var AntialiasImageRadius = ImageRadius + AntialiasMargin;

            //	内側の輪郭の円の描画
            using (var paint = new SKPaint())
            {
                paint.IsAntialias = true;
                paint.Color       = Color.White.ToSKColor();
                paint.StrokeCap   = SKStrokeCap.Round;
                paint.IsStroke    = true;
                paint.StrokeWidth = PhysicalPixelRate;
                using (var path = new SKPath())
                {
                    path.ArcTo(SKRect.Create(Center.X - AntialiasImageRadius, Center.Y - AntialiasImageRadius, AntialiasImageRadius * 2.0f, AntialiasImageRadius * 2.0f), 0.0f, 180.0f, false);
                    Canvas.DrawPath(path, paint);
                }
                using (var path = new SKPath())
                {
                    path.ArcTo(SKRect.Create(Center.X - AntialiasImageRadius, Center.Y - AntialiasImageRadius, AntialiasImageRadius * 2.0f, AntialiasImageRadius * 2.0f), 180.0f, 180.0f, false);
                    Canvas.DrawPath(path, paint);
                }
            }

            if (null == Data || !Data.Any())
            {
                using (var paint = new SKPaint())
                {
                    paint.IsAntialias = true;
                    paint.Color       = Color.Gray.ToSKColor();
                    paint.StrokeCap   = SKStrokeCap.Round;
                    if (null != Image || IsDoughnut)
                    {
                        //	一度に描画しようとしても path が繋がらないので半分に分けて描画する
                        using (var path = new SKPath())
                        {
                            path.MoveTo(Center + AngleRadiusToPoint(0.0f, AntialiasImageRadius));
                            path.LineTo(Center + AngleRadiusToPoint(0.0f, AntialiasPieRadius));
                            path.ArcTo(SKRect.Create(Center.X - AntialiasPieRadius, Center.Y - AntialiasPieRadius, AntialiasPieRadius * 2.0f, AntialiasPieRadius * 2.0f), 0.0f, 180.0f, false);
                            //path.LineTo(Center + AngleRadiusToPoint(180.0f, AntialiasPieRadius));
                            path.LineTo(Center + AngleRadiusToPoint(180.0f, ImageRadius));
                            path.ArcTo(SKRect.Create(Center.X - AntialiasImageRadius, Center.Y - AntialiasImageRadius, AntialiasImageRadius * 2.0f, AntialiasImageRadius * 2.0f), 180.0f, -180.0f, false);
                            path.Close();
                            Canvas.DrawPath(path, paint);
                        }
                        using (var path = new SKPath())
                        {
                            path.MoveTo(Center + AngleRadiusToPoint(180.0f, AntialiasImageRadius));
                            path.LineTo(Center + AngleRadiusToPoint(180.0f, AntialiasPieRadius));
                            path.ArcTo(SKRect.Create(Center.X - AntialiasPieRadius, Center.Y - AntialiasPieRadius, AntialiasPieRadius * 2.0f, AntialiasPieRadius * 2.0f), 180.0f, 180.0f, false);
                            //path.LineTo(Center + AngleRadiusToPoint(180.0f, AntialiasPieRadius));
                            path.LineTo(Center + AngleRadiusToPoint(360.0f, AntialiasImageRadius));
                            path.ArcTo(SKRect.Create(Center.X - AntialiasImageRadius, Center.Y - AntialiasImageRadius, AntialiasImageRadius * 2.0f, AntialiasImageRadius * 2.0f), 360.0f, -180.0f, false);
                            path.Close();
                            Canvas.DrawPath(path, paint);
                        }
                    }
                    else
                    {
                        Canvas.DrawCircle(Center.X, Center.Y, AntialiasPieRadius, paint);
                    }
                }
            }
            else
            {
                //	パイ本体の描画
                var TotalVolume  = GetTotalVolume();
                var CurrentAngle = GetStartAngle();
                foreach (var Pie in Data)
                {
                    var CurrentAngleVolume = (float)((Pie.Volume / TotalVolume) * 360.0);
                    var NextAngle          = CurrentAngle + CurrentAngleVolume;
                    using (var paint = new SKPaint())
                    {
                        paint.IsAntialias = true;
                        paint.Color       = Pie.Color.ToSKColor();
                        paint.StrokeCap   = SKStrokeCap.Round;
                        if (Pie.Volume < TotalVolume)
                        {
                            using (var path = new SKPath())
                            {
                                if (null != Image || IsDoughnut)
                                {
                                    path.MoveTo(Center + AngleRadiusToPoint(CurrentAngle, AntialiasImageRadius));
                                    path.LineTo(Center + AngleRadiusToPoint(CurrentAngle, AntialiasPieRadius));
                                    path.ArcTo(SKRect.Create(Center.X - AntialiasPieRadius, Center.Y - AntialiasPieRadius, AntialiasPieRadius * 2.0f, AntialiasPieRadius * 2.0f), CurrentAngle, CurrentAngleVolume, false);
                                    //path.LineTo(Center + AngleRadiusToPoint(NextAngle, AntialiasPieRadius));
                                    path.LineTo(Center + AngleRadiusToPoint(NextAngle, AntialiasImageRadius));
                                    path.ArcTo(SKRect.Create(Center.X - AntialiasImageRadius, Center.Y - AntialiasImageRadius, AntialiasImageRadius * 2.0f, AntialiasImageRadius * 2.0f), NextAngle, -CurrentAngleVolume, false);
                                }
                                else
                                {
                                    path.MoveTo(Center);
                                    path.LineTo(Center + AngleRadiusToPoint(CurrentAngle, AntialiasPieRadius));
                                    path.ArcTo(SKRect.Create(Center.X - AntialiasPieRadius, Center.Y - AntialiasPieRadius, AntialiasPieRadius * 2.0f, AntialiasPieRadius * 2.0f), CurrentAngle, CurrentAngleVolume, false);
                                    path.LineTo(Center + AngleRadiusToPoint(NextAngle, AntialiasPieRadius));
                                    path.LineTo(Center);
                                }
                                path.Close();
                                Canvas.DrawPath(path, paint);
                            }
                        }
                        else
                        {
                            //	TotalVolume <= Pie.Volume な時に上の処理ではパイが描画されないことがある。
                            if (null != Image || IsDoughnut)
                            {
                                //	一度に描画しようとしても path が繋がらないので半分に分けて描画する
                                using (var path = new SKPath())
                                {
                                    path.MoveTo(Center + AngleRadiusToPoint(0.0f, AntialiasImageRadius));
                                    path.LineTo(Center + AngleRadiusToPoint(0.0f, AntialiasPieRadius));
                                    path.ArcTo(SKRect.Create(Center.X - AntialiasPieRadius, Center.Y - AntialiasPieRadius, AntialiasPieRadius * 2.0f, AntialiasPieRadius * 2.0f), 0.0f, 180.0f, false);
                                    //path.LineTo(Center + AngleRadiusToPoint(180.0f, AntialiasPieRadius));
                                    path.LineTo(Center + AngleRadiusToPoint(180.0f, AntialiasImageRadius));
                                    path.ArcTo(SKRect.Create(Center.X - AntialiasImageRadius, Center.Y - AntialiasImageRadius, AntialiasImageRadius * 2.0f, AntialiasImageRadius * 2.0f), 180.0f, -180.0f, false);
                                    path.Close();
                                    Canvas.DrawPath(path, paint);
                                }
                                using (var path = new SKPath())
                                {
                                    path.MoveTo(Center + AngleRadiusToPoint(180.0f, AntialiasImageRadius));
                                    path.LineTo(Center + AngleRadiusToPoint(180.0f, AntialiasPieRadius));
                                    path.ArcTo(SKRect.Create(Center.X - AntialiasPieRadius, Center.Y - AntialiasPieRadius, AntialiasPieRadius * 2.0f, AntialiasPieRadius * 2.0f), 180.0f, 180.0f, false);
                                    //path.LineTo(Center + AngleRadiusToPoint(180.0f, AntialiasPieRadius));
                                    path.LineTo(Center + AngleRadiusToPoint(360.0f, AntialiasImageRadius));
                                    path.ArcTo(SKRect.Create(Center.X - AntialiasImageRadius, Center.Y - AntialiasImageRadius, AntialiasImageRadius * 2.0f, AntialiasImageRadius * 2.0f), 360.0f, -180.0f, false);
                                    path.Close();
                                    Canvas.DrawPath(path, paint);
                                }
                            }
                            else
                            {
                                Canvas.DrawCircle(Center.X, Center.Y, AntialiasPieRadius, paint);
                            }
                        }
                    }
                    CurrentAngle = NextAngle;
                }

                //	セパレーターの描画
                CurrentAngle = GetStartAngle();
                foreach (var Pie in Data)
                {
                    var CurrentAngleVolume = (float)((Pie.Volume / TotalVolume) * 360.0);
                    var NextAngle          = CurrentAngle + CurrentAngleVolume;
                    using (var paint = new SKPaint())
                    {
                        paint.IsAntialias = true;
                        paint.Color       = Color.White.ToSKColor();
                        paint.StrokeCap   = SKStrokeCap.Round;
                        paint.IsStroke    = true;
                        paint.StrokeWidth = PhysicalPixelRate;
                        using (var path = new SKPath())
                        {
                            if (null != Image || IsDoughnut)
                            {
                                //path.ArcTo(SKRect.Create(Center.X - ImageRadius, Center.Y - ImageRadius, ImageRadius * 2.0f, ImageRadius * 2.0f), CurrentAngle, CurrentAngleVolume, false);
                                path.MoveTo(Center + AngleRadiusToPoint(CurrentAngle, AntialiasImageRadius));
                            }
                            else
                            {
                                path.MoveTo(Center);
                            }
                            path.LineTo(Center + AngleRadiusToPoint(CurrentAngle, AntialiasPieRadius));
                            Canvas.DrawPath(path, paint);
                        }
                    }
                    CurrentAngle = NextAngle;
                }

                //	パイ・テキストの描画
                if (null == Image && !IsDoughnut)
                {
                    foreach (var Pie in Data)
                    {
                        var CurrentAngleVolume = (float)((Pie.Volume / TotalVolume) * 360.0);
                        var NextAngle          = CurrentAngle + CurrentAngleVolume;
                        if (!String.IsNullOrWhiteSpace(Pie.Text) || !String.IsNullOrWhiteSpace(Pie.DisplayVolume))
                        {
                            using (var paint = new SKPaint())
                            {
                                paint.IsAntialias = true;
                                paint.StrokeCap   = SKStrokeCap.Round;
                                using (var path = new SKPath())
                                {
                                    paint.TextSize    = FontSize * PhysicalPixelRate;
                                    paint.IsAntialias = true;
                                    paint.Color       = Color.White.ToSKColor();
                                    paint.TextAlign   = SKTextAlign.Center;
                                    paint.Typeface    = Font;

                                    var CenterAngle = (CurrentAngle + NextAngle) / 2.0f;
                                    var HalfRadius  = AntialiasPieRadius / 2.0f;
                                    var TextCenter  = Center + AngleRadiusToPoint(CenterAngle, HalfRadius);

                                    if (!String.IsNullOrWhiteSpace(Pie.Text))
                                    {
                                        Canvas.DrawText
                                        (
                                            Pie.Text,
                                            TextCenter.X,
                                            TextCenter.Y - (paint.TextSize / 2.0f),
                                            paint
                                        );
                                    }
                                    if (!String.IsNullOrWhiteSpace(Pie.DisplayVolume))
                                    {
                                        Canvas.DrawText
                                        (
                                            Pie.DisplayVolume,
                                            TextCenter.X,
                                            TextCenter.Y + (paint.TextSize / 2.0f),
                                            paint
                                        );
                                    }

                                    paint.Typeface = null;
                                }
                            }
                        }
                        CurrentAngle = NextAngle;
                    }
                }
            }

            //	外側の輪郭の円の描画
            using (var paint = new SKPaint())
            {
                paint.IsAntialias = true;
                paint.Color       = Color.White.ToSKColor();
                paint.StrokeCap   = SKStrokeCap.Round;
                paint.IsStroke    = true;
                paint.StrokeWidth = PhysicalPixelRate;
                using (var path = new SKPath())
                {
                    path.ArcTo(SKRect.Create(Center.X - AntialiasPieRadius, Center.Y - AntialiasPieRadius, AntialiasPieRadius * 2.0f, AntialiasPieRadius * 2.0f), 0.0f, 180.0f, false);
                    Canvas.DrawPath(path, paint);
                }
                using (var path = new SKPath())
                {
                    path.ArcTo(SKRect.Create(Center.X - AntialiasPieRadius, Center.Y - AntialiasPieRadius, AntialiasPieRadius * 2.0f, AntialiasPieRadius * 2.0f), 180.0f, 180.0f, false);
                    Canvas.DrawPath(path, paint);
                }
            }
        }
Пример #5
0
        public override void PreProcess(SKCanvas canvas, SKRect bounds, SKPaint paint)
        {
            // TODO: Lets see whether we can tell Artemis we only support layers
            if (ProfileElement is not Layer layer || !layer.Leds.Any())
            {
                return;
            }

            // Find out how many LEDs to reveal according to the current percentage
            int toReveal = Properties.RoundingFunction.CurrentValue switch
            {
                RoundingFunction.Round => (int)Math.Round(layer.Leds.Count / 100.0 * Math.Min(100, Properties.Percentage.CurrentValue), MidpointRounding.AwayFromZero),
                RoundingFunction.Floor => (int)Math.Floor(layer.Leds.Count / 100.0 * Math.Min(100, Properties.Percentage.CurrentValue)),
                RoundingFunction.Ceiling => (int)Math.Ceiling(layer.Leds.Count / 100.0 * Math.Min(100, Properties.Percentage.CurrentValue)),
                _ => throw new ArgumentOutOfRangeException()
            };

            // If the amount hasn't changed, reuse the last path
            if (toReveal == _lastToReveal && Properties.MaxVisibleLeds == _lastMaxVisible && _clipPath != null)
            {
                canvas.ClipPath(_clipPath);
                return;
            }

            // Order LEDs by their position to create a nice revealing effect from left top right, top to bottom
            List <ArtemisLed> leds = Properties.LedOrder.CurrentValue switch
            {
                LedOrder.LedId => layer.Leds.OrderBy(l => l.Device.Rectangle.Left).ThenBy(l => l.Device.Rectangle.Top).ThenBy(l => l.RgbLed.Id).ToList(),
                LedOrder.Vertical => layer.Leds.OrderBy(l => l.AbsoluteRectangle.Left).ThenBy(l => l.AbsoluteRectangle.Top).ToList(),
                LedOrder.Horizontal => layer.Leds.OrderBy(l => l.AbsoluteRectangle.Top).ThenBy(l => l.AbsoluteRectangle.Left).ToList(),
                LedOrder.VerticalReversed => layer.Leds.OrderByDescending(l => l.AbsoluteRectangle.Left).ThenByDescending(l => l.AbsoluteRectangle.Top).ToList(),
                LedOrder.HorizontalReversed => layer.Leds.OrderByDescending(l => l.AbsoluteRectangle.Top).ThenByDescending(l => l.AbsoluteRectangle.Left).ToList(),
                _ => throw new ArgumentOutOfRangeException()
            };

            // Because rendering for effects is 0,0 based, zero out the position of LEDs starting at the top-left
            float offsetX = leds.Min(l => l.AbsoluteRectangle.Left);
            float offsetY = leds.Min(l => l.AbsoluteRectangle.Top);

            // Create or reset the path
            if (_clipPath == null)
            {
                _clipPath = new SKPath();
            }
            else
            {
                _clipPath.Reset();
            }

            IEnumerable <ArtemisLed> ledsEnumerable = leds.Take(toReveal);

            if (Properties.LimitVisibleLeds)
            {
                ledsEnumerable = ledsEnumerable.Skip(toReveal - Properties.MaxVisibleLeds);
            }
            foreach (ArtemisLed artemisLed in ledsEnumerable)
            {
                _clipPath.AddRect(SKRect.Create(
                                      artemisLed.AbsoluteRectangle.Left - offsetX,
                                      artemisLed.AbsoluteRectangle.Top - offsetY,
                                      artemisLed.AbsoluteRectangle.Width,
                                      artemisLed.AbsoluteRectangle.Height));
            }

            canvas.ClipPath(_clipPath);
            _lastMaxVisible = Properties.MaxVisibleLeds;
            _lastToReveal   = toReveal;
        }
Пример #6
0
        private void Apply(
            CheckBox field
            )
        {
            Document document = field.Document;

            foreach (Widget widget in field.Widgets)
            {
                {
                    PdfDictionary widgetDataObject = widget.BaseDataObject;
                    widgetDataObject[PdfName.DA] = new PdfString("/ZaDb 0 Tf 0 0 0 rg");
                    widgetDataObject[PdfName.MK] = new PdfDictionary(
                        new PdfName[] { PdfName.BG, PdfName.BC, PdfName.CA },
                        new PdfDirectObject[]
                    {
                        new PdfArray(new PdfDirectObject[] { PdfReal.Get(0.9412), PdfReal.Get(0.9412), PdfReal.Get(0.9412) }),
                        new PdfArray(new PdfDirectObject[] { PdfInteger.Default, PdfInteger.Default, PdfInteger.Default }),
                        new PdfString("4")
                    }
                        );
                    widgetDataObject[PdfName.BS] = new PdfDictionary(
                        new PdfName[] { PdfName.W, PdfName.S },
                        new PdfDirectObject[] { PdfReal.Get(0.8), PdfName.S }
                        );
                    widgetDataObject[PdfName.H] = PdfName.P;
                }

                Appearance       appearance       = widget.Appearance;
                AppearanceStates normalAppearance = appearance.Normal;
                SKSize           size             = widget.Box.Size;
                FormXObject      onState          = new FormXObject(document, size);
                normalAppearance[PdfName.Yes] = onState;

                //TODO:verify!!!
                //   appearance.getRollover().put(PdfName.Yes,onState);
                //   appearance.getDown().put(PdfName.Yes,onState);
                //   appearance.getRollover().put(PdfName.Off,offState);
                //   appearance.getDown().put(PdfName.Off,offState);

                float  lineWidth = 1;
                SKRect frame     = SKRect.Create(lineWidth / 2, lineWidth / 2, size.Width - lineWidth, size.Height - lineWidth);
                {
                    PrimitiveComposer composer = new PrimitiveComposer(onState);

                    if (GraphicsVisibile)
                    {
                        composer.BeginLocalState();
                        composer.SetLineWidth(lineWidth);
                        composer.SetFillColor(BackColor);
                        composer.SetStrokeColor(ForeColor);
                        composer.DrawRectangle(frame, 5);
                        composer.FillStroke();
                        composer.End();
                    }

                    BlockComposer blockComposer = new BlockComposer(composer);
                    blockComposer.Begin(frame, XAlignmentEnum.Center, YAlignmentEnum.Middle);
                    composer.SetFillColor(ForeColor);
                    composer.SetFont(
                        new StandardType1Font(
                            document,
                            StandardType1Font.FamilyEnum.ZapfDingbats,
                            true,
                            false
                            ),
                        size.Height * 0.8
                        );
                    blockComposer.ShowText(new String(new char[] { CheckSymbol }));
                    blockComposer.End();

                    composer.Flush();
                }

                FormXObject offState = new FormXObject(document, size);
                normalAppearance[PdfName.Off] = offState;
                {
                    if (GraphicsVisibile)
                    {
                        PrimitiveComposer composer = new PrimitiveComposer(offState);

                        composer.BeginLocalState();
                        composer.SetLineWidth(lineWidth);
                        composer.SetFillColor(BackColor);
                        composer.SetStrokeColor(ForeColor);
                        composer.DrawRectangle(frame, 5);
                        composer.FillStroke();
                        composer.End();

                        composer.Flush();
                    }
                }
            }
        }
Пример #7
0
        private void DrawCenter(SKCanvas Canvas)
        {
            IsInvalidCenter = false;
            IsInvalidData   = true;
            var AntialiasImageRadius = ImageRadius - AntialiasMargin;

            //	背景を塗りつぶす
            if (!IsClearCanvas)
            {
                using (var paint = new SKPaint())
                {
                    paint.IsAntialias = true;
                    paint.Color       = Color.White.ToSKColor();
                    paint.StrokeCap   = SKStrokeCap.Round;
                    Canvas.DrawCircle(Center.X, Center.Y, ImageRadius + AntialiasMargin, paint);
                }
            }

            //	イメージの描画
            if (null != Image && null != ImageData && null != ImageBitmap)
            {
                using (var paint = new SKPaint())
                {
                    var Rect = SKRect.Create
                               (
                        Center.X - AntialiasImageRadius,
                        Center.Y - AntialiasImageRadius,
                        AntialiasImageRadius * 2.0f,
                        AntialiasImageRadius * 2.0f
                               );
                    Canvas.DrawBitmap(ImageBitmap, Rect, paint);
                }
                if (ImageAlpha < 255)
                {
                    using (var paint = new SKPaint())
                    {
                        paint.IsAntialias = true;
                        paint.Color       = new SKColor(255, 255, 255, (byte)(255 - ImageAlpha));
                        paint.StrokeCap   = SKStrokeCap.Round;
                        paint.IsStroke    = false;
                        Canvas.DrawCircle(Center.X, Center.Y, AntialiasImageRadius, paint);
                    }
                }
            }
            else
            //	Altテキストの描画
            if (!String.IsNullOrWhiteSpace(AltText))
            {
                using (var paint = new SKPaint())
                {
                    paint.IsAntialias = true;
                    paint.Color       = AltTextColor.ToSKColor();
                    paint.StrokeCap   = SKStrokeCap.Round;
                    paint.TextSize    = FontSize * PhysicalPixelRate;
                    paint.TextAlign   = SKTextAlign.Center;
                    paint.Typeface    = Font;

                    Canvas.DrawText
                    (
                        AltText,
                        Center.X,
                        Center.Y + (paint.TextSize / 2.0f),
                        paint
                    );

                    paint.Typeface = null;
                }
            }

            //	輪郭の円の描画 ( これより外側の部分は DrawData() に任せる )
            using (var paint = new SKPaint())
            {
                paint.IsAntialias = true;
                paint.Color       = Color.White.ToSKColor();
                paint.StrokeCap   = SKStrokeCap.Round;
                paint.IsStroke    = true;
                paint.StrokeWidth = PhysicalPixelRate;
                using (var path = new SKPath())
                {
                    path.ArcTo(SKRect.Create(Center.X - AntialiasImageRadius, Center.Y - AntialiasImageRadius, AntialiasImageRadius * 2.0f, AntialiasImageRadius * 2.0f), 0.0f, 180.0f, false);
                    Canvas.DrawPath(path, paint);
                }
                using (var path = new SKPath())
                {
                    path.ArcTo(SKRect.Create(Center.X - AntialiasImageRadius, Center.Y - AntialiasImageRadius, AntialiasImageRadius * 2.0f, AntialiasImageRadius * 2.0f), 180.0f, 180.0f, false);
                    Canvas.DrawPath(path, paint);
                }
            }
        }
Пример #8
0
        private SKBitmap BuildThumbCollageBitmap(string[] paths, int width, int height)
        {
            var bitmap = new SKBitmap(width, height);

            using (var canvas = new SKCanvas(bitmap))
            {
                canvas.Clear(SKColors.Black);

                // determine sizes for each image that will composited into the final image
                var iSlice  = Convert.ToInt32(width * 0.23475);
                int iTrans  = Convert.ToInt32(height * .25);
                int iHeight = Convert.ToInt32(height * .70);
                var horizontalImagePadding = Convert.ToInt32(width * 0.0125);
                var verticalSpacing        = Convert.ToInt32(height * 0.01111111111111111111111111111111);
                int imageIndex             = 0;

                for (int i = 0; i < 4; i++)
                {
                    int newIndex;

                    using (var currentBitmap = GetNextValidImage(paths, imageIndex, out newIndex))
                    {
                        imageIndex = newIndex;

                        if (currentBitmap == null)
                        {
                            continue;
                        }

                        // resize to the same aspect as the original
                        int iWidth = (int)Math.Abs(iHeight * currentBitmap.Width / currentBitmap.Height);
                        using (var resizeBitmap = new SKBitmap(iWidth, iHeight, currentBitmap.ColorType, currentBitmap.AlphaType))
                        {
                            currentBitmap.Resize(resizeBitmap, SKBitmapResizeMethod.Lanczos3);
                            // determine how much to crop
                            int ix = (int)Math.Abs((iWidth - iSlice) / 2);
                            using (var image = SKImage.FromBitmap(resizeBitmap))
                            {
                                // crop image
                                using (var subset = image.Subset(SKRectI.Create(ix, 0, iSlice, iHeight)))
                                {
                                    // draw image onto canvas
                                    canvas.DrawImage(subset ?? image, (horizontalImagePadding * (i + 1)) + (iSlice * i), verticalSpacing);

                                    if (subset == null)
                                    {
                                        continue;
                                    }

                                    using (var croppedBitmap = SKBitmap.FromImage(subset))
                                    {
                                        // create reflection of image below the drawn image
                                        using (var reflectionBitmap = new SKBitmap(croppedBitmap.Width, croppedBitmap.Height / 2, croppedBitmap.ColorType, croppedBitmap.AlphaType))
                                        {
                                            // resize to half height
                                            croppedBitmap.Resize(reflectionBitmap, SKBitmapResizeMethod.Lanczos3);

                                            using (var flippedBitmap = new SKBitmap(reflectionBitmap.Width, reflectionBitmap.Height, reflectionBitmap.ColorType, reflectionBitmap.AlphaType))
                                            {
                                                using (var flippedCanvas = new SKCanvas(flippedBitmap))
                                                {
                                                    // flip image vertically
                                                    var matrix = SKMatrix.MakeScale(1, -1);
                                                    matrix.SetScaleTranslate(1, -1, 0, flippedBitmap.Height);
                                                    flippedCanvas.SetMatrix(matrix);
                                                    flippedCanvas.DrawBitmap(reflectionBitmap, 0, 0);
                                                    flippedCanvas.ResetMatrix();

                                                    // create gradient to make image appear as a reflection
                                                    var remainingHeight = height - (iHeight + (2 * verticalSpacing));
                                                    flippedCanvas.ClipRect(SKRect.Create(reflectionBitmap.Width, remainingHeight));
                                                    using (var gradient = new SKPaint())
                                                    {
                                                        gradient.IsAntialias = true;
                                                        gradient.BlendMode   = SKBlendMode.SrcOver;
                                                        gradient.Shader      = SKShader.CreateLinearGradient(new SKPoint(0, 0), new SKPoint(0, remainingHeight), new[] { new SKColor(0, 0, 0, 128), new SKColor(0, 0, 0, 208), new SKColor(0, 0, 0, 240), new SKColor(0, 0, 0, 255) }, null, SKShaderTileMode.Clamp);
                                                        flippedCanvas.DrawPaint(gradient);
                                                    }

                                                    // finally draw reflection onto canvas
                                                    canvas.DrawBitmap(flippedBitmap, (horizontalImagePadding * (i + 1)) + (iSlice * i), iHeight + (2 * verticalSpacing));
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }

            return(bitmap);
        }
Пример #9
0
        public async Task <SKImage> GenerateChartAsync(ChartSettings chart)
        {
            try
            {
                await chart.Albums.ParallelForEachAsync(async album =>
                {
                    var encodedId    = StringExtensions.ReplaceInvalidChars(album.Url.LocalPath.Replace("/music/", ""));
                    var localAlbumId = StringExtensions.TruncateLongString(encodedId, 60);

                    SKBitmap chartImage;
                    var validImage     = true;
                    Color?primaryColor = null;

                    var fileName  = localAlbumId + ".png";
                    var localPath = FMBotUtil.GlobalVars.CacheFolder + fileName;

                    if (File.Exists(localPath))
                    {
                        chartImage = SKBitmap.Decode(localPath);
                        Statistics.LastfmCachedImageCalls.Inc();
                    }
                    else
                    {
                        if (album.Images.Any() && album.Images.Large != null)
                        {
                            var url = album.Images.Large.AbsoluteUri;

                            SKBitmap bitmap;
                            try
                            {
                                var httpClient = new System.Net.Http.HttpClient();
                                var bytes      = await httpClient.GetByteArrayAsync(url);

                                Statistics.LastfmImageCalls.Inc();

                                var stream = new MemoryStream(bytes);

                                bitmap = SKBitmap.Decode(stream);
                            }
                            catch
                            {
                                bitmap     = SKBitmap.Decode(FMBotUtil.GlobalVars.ImageFolder + "loading-error.png");
                                validImage = false;
                            }

                            chartImage = bitmap;

                            if (validImage)
                            {
                                using var image        = SKImage.FromBitmap(bitmap);
                                using var data         = image.Encode(SKEncodedImageFormat.Png, 100);
                                await using var stream = File.OpenWrite(localPath);
                                data.SaveTo(stream);
                            }
                        }
                        else
                        {
                            chartImage = SKBitmap.Decode(FMBotUtil.GlobalVars.ImageFolder + "unknown.png");
                            validImage = false;
                        }
                    }

                    switch (chart.TitleSetting)
                    {
                    case TitleSetting.Titles:
                        AddTitleToChartImage(chartImage, album);
                        break;

                    case TitleSetting.ClassicTitles:
                        AddClassicTitleToChartImage(chartImage, album);
                        break;
                    }

                    if (chart.RainbowSortingEnabled)
                    {
                        primaryColor = chartImage.GetAverageRgbColor();
                    }

                    chart.ChartImages.Add(new ChartImage(chartImage, chart.Albums.IndexOf(album), validImage, primaryColor));
                });


                SKImage finalImage = null;

                using (var tempSurface = SKSurface.Create(new SKImageInfo(chart.ChartImages.First().Image.Width *chart.Width, chart.ChartImages.First().Image.Height *chart.Height)))
                {
                    var canvas = tempSurface.Canvas;

                    var offset    = 0;
                    var offsetTop = 0;
                    var heightRow = 0;

                    for (var i = 0; i < Math.Min(chart.ImagesNeeded, chart.ChartImages.Count); i++)
                    {
                        IOrderedEnumerable <ChartImage> imageList;
                        if (chart.RainbowSortingEnabled)
                        {
                            imageList = chart.ChartImages
                                        .OrderBy(o => o.PrimaryColor.Value.GetHue())
                                        .ThenBy(o =>
                                                (o.PrimaryColor.Value.R * 3 +
                                                 o.PrimaryColor.Value.G * 2 +
                                                 o.PrimaryColor.Value.B * 1));
                        }
                        else
                        {
                            imageList = chart.ChartImages.OrderBy(o => o.Index);
                        }

                        var image = imageList
                                    .Where(w => !chart.SkipArtistsWithoutImage || w.ValidImage)
                                    .ElementAt(i).Image;

                        canvas.DrawBitmap(image, SKRect.Create(offset, offsetTop, image.Width, image.Height));

                        if (i == (chart.Width - 1) || i - (chart.Width) * heightRow == chart.Width - 1)
                        {
                            offsetTop += image.Height;
                            heightRow += 1;
                            offset     = 0;
                        }
                        else
                        {
                            offset += image.Width;
                        }
                    }

                    finalImage = tempSurface.Snapshot();
                }

                return(finalImage);
            }

            finally
            {
                foreach (var image in chart.ChartImages.Select(s => s.Image))
                {
                    image.Dispose();
                }
            }
        }
Пример #10
0
        private bool DrawOntoSurface(IntPtr handle, SKSurface surface)
        {
            var hwnd = Hwnd.ObjectFromHandle(handle);

            var x = 0;
            var y = 0;

            XplatUI.driver.ClientToScreen(hwnd.client_window, ref x, ref y);

            var width         = 0;
            var height        = 0;
            var client_width  = 0;
            var client_height = 0;


            if (hwnd.hwndbmp != null && hwnd.Mapped && hwnd.Visible && !hwnd.zombie)
            {
                // setup clip
                var parent = hwnd;
                surface.Canvas.ClipRect(
                    SKRect.Create(0, 0, Screen.PrimaryScreen.Bounds.Width * 2,
                                  Screen.PrimaryScreen.Bounds.Height * 2), (SKClipOperation)5);

                while (parent != null)
                {
                    var xp = 0;
                    var yp = 0;
                    XplatUI.driver.ClientToScreen(parent.client_window, ref xp, ref yp);

                    surface.Canvas.ClipRect(SKRect.Create(xp, yp, parent.Width, parent.Height),
                                            SKClipOperation.Intersect);

                    /*
                     * surface.Canvas.DrawRect(xp, yp, parent.Width, parent.Height,
                     *  new SKPaint()
                     *  {
                     *
                     *      Color = new SKColor(255, 0, 0),
                     *      Style = SKPaintStyle.Stroke
                     *
                     *
                     *  });
                     */
                    parent = parent.parent;
                }

                Monitor.Enter(XplatUIMine.paintlock);

                if (hwnd.ClientWindow != hwnd.WholeWindow)
                {
                    var frm = System.Windows.Forms.Control.FromHandle(hwnd.ClientWindow) as Form;

                    Hwnd.Borders borders = new Hwnd.Borders();

                    if (frm != null)
                    {
                        borders = Hwnd.GetBorders(frm.GetCreateParams(), null);

                        surface.Canvas.ClipRect(
                            SKRect.Create(0, 0, Screen.PrimaryScreen.Bounds.Width * 2,
                                          Screen.PrimaryScreen.Bounds.Height * 2), (SKClipOperation)5);
                    }

                    if (surface.Canvas.DeviceClipBounds.Width > 0 &&
                        surface.Canvas.DeviceClipBounds.Height > 0)
                    {
                        if (hwnd.hwndbmpNC != null)
                        {
                            surface.Canvas.DrawImage(hwnd.hwndbmpNC,
                                                     new SKPoint(x - borders.left, y - borders.top),
                                                     new SKPaint()
                            {
                                FilterQuality = SKFilterQuality.Low
                            });
                        }

                        surface.Canvas.ClipRect(
                            SKRect.Create(x, y, hwnd.width - borders.right - borders.left,
                                          hwnd.height - borders.top - borders.bottom), SKClipOperation.Intersect);

                        surface.Canvas.DrawImage(hwnd.hwndbmp,
                                                 new SKPoint(x, y),
                                                 new SKPaint()
                        {
                            FilterQuality = SKFilterQuality.Low
                        });
                    }
                    else
                    {
                        Monitor.Exit(XplatUIMine.paintlock);
                        return(true);
                    }
                }
                else
                {
                    if (surface.Canvas.DeviceClipBounds.Width > 0 &&
                        surface.Canvas.DeviceClipBounds.Height > 0)
                    {
                        surface.Canvas.DrawImage(hwnd.hwndbmp,
                                                 new SKPoint(x + 0, y + 0),
                                                 new SKPaint()
                        {
                            FilterQuality = SKFilterQuality.Low
                        });

/*
 *                      surface.Canvas.DrawText(Control.FromHandle(hwnd.ClientWindow).Name,
 *                          new SKPoint(x, y + 15),
 *                          new SKPaint() {Color = SKColor.Parse("55ffff00")});
 *                      /*surface.Canvas.DrawText(hwnd.ClientWindow.ToString(), new SKPoint(x,y+15),
 *                          new SKPaint() {Color = SKColor.Parse("ffff00")});*/
                    }
                    else
                    {
                        Monitor.Exit(XplatUIMine.paintlock);
                        return(true);
                    }
                }

                Monitor.Exit(XplatUIMine.paintlock);
            }

            //surface.Canvas.DrawText(x + " " + y, x, y+10, new SKPaint() { Color =  SKColors.Red});

            if (hwnd.Mapped && hwnd.Visible)
            {
                IEnumerable <Hwnd> children;
                lock (Hwnd.windows)
                    children = Hwnd.windows.OfType <System.Collections.DictionaryEntry>()
                               .Where(hwnd2 =>
                    {
                        var Key   = (IntPtr)hwnd2.Key;
                        var Value = (Hwnd)hwnd2.Value;
                        if (Value.ClientWindow == Key && Value.Parent == hwnd && Value.Visible &&
                            Value.Mapped && !Value.zombie)
                        {
                            return(true);
                        }
                        return(false);
                    }).Select(a => (Hwnd)a.Value).ToArray();

                children = children.OrderBy((hwnd2) =>
                {
                    var info = XplatUIMine.GetInstance().GetZOrder(hwnd2.client_window);
                    if (info.top)
                    {
                        return(1000);
                    }
                    if (info.bottom)
                    {
                        return(0);
                    }
                    return(500);
                });

                foreach (var child in children)
                {
                    DrawOntoSurface(child.ClientWindow, surface);
                }
            }

            return(true);
        }
Пример #11
0
        public void DrawSquare(SKCanvas thisCanvas, float width, float height)
        {
            var bounds = SKRect.Create(0, 0, width, height);

            _redPenBrush !.StrokeWidth       = bounds.Width / 20;
            _slateGrayPenBrush !.StrokeWidth = bounds.Width / 30;
            _blackPenBrush !.StrokeWidth     = bounds.Width / 20;
            _darkGrayPenBrush !.StrokeWidth  = bounds.Width / 30;
            MiscHelpers.DefaultFont          = "Verdana";
            var thisPercs = MiscHelpers.EnumLinearGradientPercent.Angle45;

            if (IsFlipped == true)
            {
                if (IsMine == true || Flagged == true)
                {
                    var firstColor  = new SKColor(255, 255, 255, 100);
                    var secondColor = new SKColor(0, 0, 0, 100);
                    var secondBrush = MiscHelpers.GetLinearGradientPaint(firstColor, secondColor, bounds, thisPercs);
                    thisCanvas.DrawOval(bounds.Left + (bounds.Width / 2), bounds.Top + (bounds.Width / 2), bounds.Width / 4, bounds.Height / 4, _redSolidBrush);
                    // well see how the second part comes along (could be iffy)(?)
                    thisCanvas.DrawOval(bounds.Left + (bounds.Width / 2), bounds.Top + (bounds.Width / 2), bounds.Width / 4, bounds.Height / 4, secondBrush);
                }
                else if (NeighborMines > 0)
                {
                    var textPaint = MiscHelpers.GetTextPaint(SKColors.Aqua, (bounds.Height * 3) / 4);
                    thisCanvas.DrawCustomText(NeighborMines.ToString(), TextExtensions.EnumLayoutOptions.Center, TextExtensions.EnumLayoutOptions.Center, textPaint, bounds, out _); // i think
                }
                if (Flagged == true)
                {
                    thisCanvas.DrawLine(bounds.Location.X, bounds.Location.Y, bounds.Location.X + bounds.Width, bounds.Location.Y + bounds.Height, _blackPenBrush);
                    thisCanvas.DrawLine(bounds.Location.X + bounds.Width, bounds.Location.Y, bounds.Location.X, bounds.Location.Y + bounds.Height, _blackPenBrush);
                }
            }
            else
            {
                SKRect otherRect;
                otherRect = SKRect.Create(bounds.Location.X + (bounds.Width / 6), bounds.Location.Y + (bounds.Height / 6), (bounds.Width * 2) / 3, (bounds.Height * 2) / 3);
                SKColor firstColor;
                SKColor secondColor;
                SKPaint currentPaint;
                if (Pressed == true)
                {
                    currentPaint = _darkGrayPenBrush;
                    firstColor   = new SKColor(0, 0, 0, 150);
                    secondColor  = new SKColor(255, 255, 255, 150);
                }
                else
                {
                    currentPaint = _slateGrayPenBrush;
                    firstColor   = new SKColor(255, 255, 255, 150);
                    secondColor  = new SKColor(0, 0, 0, 150);
                }
                var tempPaint = MiscHelpers.GetLinearGradientPaint(firstColor, secondColor, bounds, thisPercs);
                thisCanvas.DrawRect(bounds, tempPaint);
                thisCanvas.DrawRect(otherRect, currentPaint);
                if (Flagged == true)
                {
                    SKPath ThisPath = new SKPath();
                    ThisPath.MoveTo(bounds.Location.X + (bounds.Width / 2), bounds.Location.Y + (bounds.Height / 4));
                    ThisPath.LineTo(bounds.Location.X + ((bounds.Width * 3) / 4), bounds.Location.Y + ((bounds.Height * 3) / 8));
                    ThisPath.LineTo(bounds.Location.X + (bounds.Width / 2), bounds.Location.Y + (bounds.Height / 2));
                    thisCanvas.DrawPath(ThisPath, _redSolidBrush);
                    thisCanvas.DrawLine(bounds.Location.X + (bounds.Width / 2), bounds.Location.Y + ((bounds.Height * 3) / 4), bounds.Location.X + (bounds.Width / 2), bounds.Location.Y + (bounds.Height / 4), _redPenBrush);
                }
            }
            thisCanvas.DrawRect(bounds, _slateGrayPenBrush);
        }
Пример #12
0
        protected void OnSkiaPaint(SKSurface e)
        {
            try
            {
                var surface = e;

                surface.Canvas.Clear(SKColors.Gray);

                surface.Canvas.DrawCircle(0, 0, 50, new SKPaint()
                {
                    Color = SKColor.Parse("ff0000")
                });

                surface.Canvas.Scale((float)scale.Width, (float)scale.Height);

                foreach (Form form in Application.OpenForms.Select(a => a).ToArray())
                {
                    if (form.IsHandleCreated)
                    {
                        if (form is MainV2 && form.WindowState != FormWindowState.Maximized)
                        {
                            form.BeginInvokeIfRequired(() => { form.WindowState = FormWindowState.Maximized; });
                        }

                        try
                        {
                            DrawOntoSurface(form.Handle, surface);
                        }
                        catch (Exception ex)
                        {
                            Console.WriteLine(ex);
                        }
                    }
                }

                IEnumerable <Hwnd> menu;
                lock (Hwnd.windows)
                    menu = Hwnd.windows.Values.OfType <Hwnd>()
                           .Where(hw => hw.topmost && hw.Mapped && hw.Visible).ToArray();
                foreach (Hwnd hw in menu)
                {
                    if (hw.topmost && hw.Mapped && hw.Visible)
                    {
                        var ctlmenu = System.Windows.Forms.Control.FromHandle(hw.ClientWindow);
                        if (ctlmenu != null)
                        {
                            DrawOntoSurface(hw.ClientWindow, surface);
                        }
                    }
                }

                {
                    surface.Canvas.ClipRect(
                        SKRect.Create(0, 0, Screen.PrimaryScreen.Bounds.Width * 2,
                                      Screen.PrimaryScreen.Bounds.Height * 2), (SKClipOperation)5);

                    var path = new SKPath();

                    path.MoveTo(cursorPoints.First());
                    cursorPoints.ForEach(a => path.LineTo(a));
                    path.Transform(new SKMatrix(1, 0, XplatUI.driver.MousePosition.X, 0, 1,
                                                XplatUI.driver.MousePosition.Y, 0, 0, 1));

                    surface.Canvas.DrawPath(path,
                                            new SKPaint()
                    {
                        Color = SKColors.White, Style = SKPaintStyle.Fill, StrokeJoin = SKStrokeJoin.Miter
                    });
                    surface.Canvas.DrawPath(path,
                                            new SKPaint()
                    {
                        Color       = SKColors.Black, Style = SKPaintStyle.Stroke, StrokeJoin = SKStrokeJoin.Miter,
                        IsAntialias = true
                    });
                }

                surface.Canvas.Flush();

                //return;

                surface.Canvas.ClipRect(new SKRect(0, 0, Screen.PrimaryScreen.Bounds.Right * 2,
                                                   Screen.PrimaryScreen.Bounds.Bottom * 2), (SKClipOperation)5);

                /*surface.Canvas.DrawText("PixelScreenSize " + Device.Info.PixelScreenSize.ToString(),
                 *  new SKPoint(50, 10), new SKPaint() {Color = SKColor.Parse("ffff00")});
                 */

                surface.Canvas.DrawText("screen " + Screen.PrimaryScreen.ToString(), new SKPoint(50, 30),
                                        new SKPaint()
                {
                    Color = SKColor.Parse("ffff00")
                });

                int mx = 0, my = 0;
                XplatUI.driver.GetCursorPos(IntPtr.Zero, out mx, out my);

                surface.Canvas.DrawText("mouse " + XplatUI.driver.MousePosition.ToString(), new SKPoint(50, 50),
                                        new SKPaint()
                {
                    Color = SKColor.Parse("ffff00")
                });
                surface.Canvas.DrawText(mx + " " + my, new SKPoint(50, 70),
                                        new SKPaint()
                {
                    Color = SKColor.Parse("ffff00")
                });


                if (Application.OpenForms.Count > 0 &&
                    Application.OpenForms[Application.OpenForms.Count - 1].IsHandleCreated)
                {
                    var x = XplatUI.driver.MousePosition.X;
                    var y = XplatUI.driver.MousePosition.Y;

                    XplatUI.driver.ScreenToClient(Application.OpenForms[Application.OpenForms.Count - 1].Handle,
                                                  ref x,
                                                  ref y);

                    var ctl = XplatUIMine.FindControlAtPoint(Application.OpenForms[Application.OpenForms.Count - 1],
                                                             new Point(x, y));
                    if (ctl != null)
                    {
                        XplatUI.driver.ScreenToClient(ctl.Handle, ref mx, ref my);
                        surface.Canvas.DrawText("client " + mx + " " + my, new SKPoint(50, 90),
                                                new SKPaint()
                        {
                            Color = SKColor.Parse("ffff00")
                        });

                        surface.Canvas.DrawRect(x, y, ctl.Width, ctl.Height, new SKPaint()
                        {
                            Color = SKColors.Red, Style = SKPaintStyle.Stroke
                        });

                        surface.Canvas.DrawText(ctl?.ToString(), new SKPoint(50, 130),
                                                new SKPaint()
                        {
                            Color = SKColor.Parse("ffff00")
                        });

                        var hwnd = Hwnd.ObjectFromHandle(ctl.Handle);

                        surface.Canvas.DrawText(ctl.Location.ToString(), new SKPoint(50, 150),
                                                new SKPaint()
                        {
                            Color = SKColor.Parse("ffff00")
                        });
                    }
                }

                surface.Canvas.DrawText("!", new SKPoint(XplatUI.driver.MousePosition.X,
                                                         XplatUI.driver.MousePosition.Y),
                                        new SKPaint()
                {
                    Color = SKColor.Parse("ffff00")
                });
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }
            finally
            {
            }
        }
Пример #13
0
 private static SKRect ToSkRect(Rectangle bounds)
 {
     return(SKRect.Create(bounds.X, bounds.Y, bounds.Width, bounds.Height));
 }
Пример #14
0
        void OnCanvasViewPaintSurface(object sender, SKPaintSurfaceEventArgs args)
        {
            SKImageInfo info    = args.Info;
            SKSurface   surface = args.Surface;
            SKCanvas    canvas  = surface.Canvas;

            canvas.Clear();

            // Make image into bitmap
            SKBitmap bitmap = SKBitmap.Decode(ViewModel.Image.GetStreamWithImageRotatedForExternalStorage());

            // Find rectangle to fit bitmap
            float scale = Math.Min((float)info.Width / bitmap.Width,
                                   (float)info.Height / bitmap.Height);
            SKRect rect = SKRect.Create(scale * bitmap.Width,
                                        scale * bitmap.Height);
            float x = (info.Width - rect.Width) / 2;
            float y = (info.Height - rect.Height) / 2;

            rect.Offset(x, y);

            // Draw the image
            canvas.DrawBitmap(bitmap, rect);

            // Prep rectangle paint
            var rectPaint = new SKPaint
            {
                Color       = new SKColor(255, 0, 0),
                IsStroke    = true,
                StrokeWidth = 2
            };

            // Prep text paint
            var textPaint = new SKPaint
            {
                Color    = new SKColor(255, 0, 0),
                TextSize = 48
            };

            // Draw the face boxes
            ViewModel.Faces.ToList().ForEach(face =>
            {
                var faceRect = SKRect.Create(scale * face.FaceRectangle.Left + x,
                                             scale * face.FaceRectangle.Top + y,
                                             scale * face.FaceRectangle.Width,
                                             scale * face.FaceRectangle.Height);

                canvas.DrawRect(faceRect, rectPaint);

                canvas.DrawText(ViewModel.Faces.IndexOf(face).ToString(),
                                (scale * face.FaceRectangle.Left + x) + (scale * face.FaceRectangle.Width / 2),
                                (scale * face.FaceRectangle.Top + y),
                                textPaint);

                // If landmarks are present, draw them too!
                if (face.FaceLandmarks != null)
                {
                    var landmarkPaint = new SKPaint
                    {
                        Color       = new SKColor(255, 0, 0),
                        StrokeWidth = 6
                    };

                    face.FaceLandmarks.GetType().GetProperties().ToList().ForEach(landmark =>
                    {
                        if (landmark.PropertyType == typeof(Coordinate))
                        {
                            var coord = (Coordinate)landmark.GetValue(face.FaceLandmarks);

                            canvas.DrawPoint((float)(scale * coord.X + x), (float)(scale * coord.Y + y), landmarkPaint);
                        }
                    });
                }
            });
        }
Пример #15
0
        private void Populate(Document document)
        {
            Page page = new Page(document);

            document.Pages.Add(page);

            PrimitiveComposer        composer = new PrimitiveComposer(page);
            fonts::StandardType1Font font     = new fonts::StandardType1Font(document, fonts::StandardType1Font.FamilyEnum.Courier, true, false);

            composer.SetFont(font, 12);

            // Sticky note.
            composer.ShowText("Sticky note annotation:", new SKPoint(35, 35));
            new StickyNote(page, new SKPoint(50, 50), "Text of the Sticky note annotation")
            {
                IconType = StickyNote.IconTypeEnum.Note,
                Color    = DeviceRGBColor.Get(SKColors.Yellow),
                Popup    = new Popup(
                    page,
                    SKRect.Create(200, 25, 200, 75),
                    "Text of the Popup annotation (this text won't be visible as associating popups to markup annotations overrides the former's properties with the latter's)"
                    ),
                Author  = "Stefano",
                Subject = "Sticky note",
                IsOpen  = true
            };
            new StickyNote(page, new SKPoint(80, 50), "Text of the Help sticky note annotation")
            {
                IconType = StickyNote.IconTypeEnum.Help,
                Color    = DeviceRGBColor.Get(SKColors.Pink),
                Author   = "Stefano",
                Subject  = "Sticky note",
                Popup    = new Popup(
                    page,
                    SKRect.Create(400, 25, 200, 75),
                    "Text of the Popup annotation (this text won't be visible as associating popups to markup annotations overrides the former's properties with the latter's)"
                    )
            };
            new StickyNote(page, new SKPoint(110, 50), "Text of the Comment sticky note annotation")
            {
                IconType = StickyNote.IconTypeEnum.Comment,
                Color    = DeviceRGBColor.Get(SKColors.Green),
                Author   = "Stefano",
                Subject  = "Sticky note"
            };
            new StickyNote(page, new SKPoint(140, 50), "Text of the Key sticky note annotation")
            {
                IconType = StickyNote.IconTypeEnum.Key,
                Color    = DeviceRGBColor.Get(SKColors.Blue),
                Author   = "Stefano",
                Subject  = "Sticky note"
            };

            // Callout.
            composer.ShowText("Callout note annotation:", new SKPoint(35, 85));
            new FreeText(page, SKRect.Create(250, 90, 150, 70), "Text of the Callout note annotation")
            {
                Line = new FreeText.CalloutLine(
                    page,
                    new SKPoint(100, 100),
                    new SKPoint(150, 125),
                    new SKPoint(250, 125)
                    ),
                Type         = FreeText.TypeEnum.Callout,
                LineEndStyle = LineEndStyleEnum.OpenArrow,
                Border       = new Border(1),
                Color        = DeviceRGBColor.Get(SKColors.Yellow)
            };

            // File attachment.
            composer.ShowText("File attachment annotation:", new SKPoint(35, 135));
            new FileAttachment(
                page,
                SKRect.Create(50, 150, 15, 20),
                "Text of the File attachment annotation",
                FileSpecification.Get(
                    EmbeddedFile.Get(document, GetResourcePath("images" + Path.DirectorySeparatorChar + "gnu.jpg")),
                    "happyGNU.jpg")
                )
            {
                IconType = FileAttachment.IconTypeEnum.PaperClip,
                Author   = "Stefano",
                Subject  = "File attachment"
            };

            composer.ShowText("Line annotation:", new SKPoint(35, 185));
            {
                composer.BeginLocalState();
                composer.SetFont(font, 10);

                // Arrow line.
                composer.ShowText("Arrow:", new SKPoint(50, 200));
                new Line(
                    page,
                    new SKPoint(50, 260),
                    new SKPoint(200, 210),
                    "Text of the Arrow line annotation",
                    DeviceRGBColor.Get(SKColors.Black))
                {
                    StartStyle     = LineEndStyleEnum.Circle,
                    EndStyle       = LineEndStyleEnum.ClosedArrow,
                    CaptionVisible = true,
                    FillColor      = DeviceRGBColor.Get(SKColors.Green),
                    Author         = "Stefano",
                    Subject        = "Arrow line"
                };

                // Dimension line.
                composer.ShowText("Dimension:", new SKPoint(300, 200));
                new Line(
                    page,
                    new SKPoint(300, 220),
                    new SKPoint(500, 220),
                    "Text of the Dimension line annotation",
                    DeviceRGBColor.Get(SKColors.Blue)
                    )
                {
                    LeaderLineLength          = 20,
                    LeaderLineExtensionLength = 10,
                    StartStyle     = LineEndStyleEnum.OpenArrow,
                    EndStyle       = LineEndStyleEnum.OpenArrow,
                    Border         = new Border(1),
                    CaptionVisible = true,
                    Author         = "Stefano",
                    Subject        = "Dimension line"
                };

                composer.End();
            }

            var path = new SKPath();

            path.MoveTo(new SKPoint(50, 320));
            path.LineTo(new SKPoint(70, 305));
            path.LineTo(new SKPoint(110, 335));
            path.LineTo(new SKPoint(130, 320));
            path.LineTo(new SKPoint(110, 305));
            path.LineTo(new SKPoint(70, 335));
            path.LineTo(new SKPoint(50, 320));
            // Scribble.
            composer.ShowText("Scribble annotation:", new SKPoint(35, 285));
            new Scribble(
                page,
                new List <SKPath> {
                path
            },
                "Text of the Scribble annotation",
                DeviceRGBColor.Get(SKColors.Orange))
            {
                Border  = new Border(1, new LineDash(new double[] { 5, 2, 2, 2 })),
                Author  = "Stefano",
                Subject = "Scribble"
            };

            // Rectangle.
            composer.ShowText("Rectangle annotation:", new SKPoint(35, 350));
            new PdfClown.Documents.Interaction.Annotations.Rectangle(
                page,
                SKRect.Create(50, 370, 100, 30),
                "Text of the Rectangle annotation")
            {
                Color   = DeviceRGBColor.Get(SKColors.Red),
                Border  = new Border(1, new LineDash(new double[] { 5 })),
                Author  = "Stefano",
                Subject = "Rectangle",
                Popup   = new Popup(
                    page,
                    SKRect.Create(200, 325, 200, 75),
                    "Text of the Popup annotation (this text won't be visible as associating popups to markup annotations overrides the former's properties with the latter's)"
                    )
            };

            // Ellipse.
            composer.ShowText("Ellipse annotation:", new SKPoint(35, 415));
            new Ellipse(
                page,
                SKRect.Create(50, 440, 100, 30),
                "Text of the Ellipse annotation")
            {
                BorderEffect = new BorderEffect(BorderEffect.TypeEnum.Cloudy, 1),
                FillColor    = DeviceRGBColor.Get(SKColors.Cyan),
                Color        = DeviceRGBColor.Get(SKColors.Black),
                Author       = "Stefano",
                Subject      = "Ellipse"
            };

            // Rubber stamp.
            composer.ShowText("Rubber stamp annotations:", new SKPoint(35, 505));
            {
                fonts::Font stampFont = fonts::Font.Get(document, GetResourcePath("fonts" + Path.DirectorySeparatorChar + "TravelingTypewriter.otf"));
                new Stamp(
                    page,
                    new SKPoint(75, 570),
                    "This is a round custom stamp",
                    new StampAppearanceBuilder(document, StampAppearanceBuilder.TypeEnum.Round, "Done", 50, stampFont)
                    .Build()
                    )
                {
                    Rotation = -10,
                    Author   = "Stefano",
                    Subject  = "Custom stamp"
                };

                new Stamp(
                    page,
                    new SKPoint(210, 570),
                    "This is a squared (and round-cornered) custom stamp",
                    new StampAppearanceBuilder(document, StampAppearanceBuilder.TypeEnum.Squared, "Classified", 150, stampFont)
                {
                    Color = DeviceRGBColor.Get(SKColors.Orange)
                }.Build()
                    )
                {
                    Rotation = 15,
                    Author   = "Stefano",
                    Subject  = "Custom stamp"
                };

                fonts::Font stampFont2 = fonts::Font.Get(document, GetResourcePath("fonts" + Path.DirectorySeparatorChar + "MgOpenCanonicaRegular.ttf"));
                new Stamp(
                    page,
                    new SKPoint(350, 570),
                    "This is a striped custom stamp",
                    new StampAppearanceBuilder(document, StampAppearanceBuilder.TypeEnum.Striped, "Out of stock", 100, stampFont2)
                {
                    Color = DeviceRGBColor.Get(SKColors.Gray)
                }.Build()
                    )
                {
                    Rotation = 90,
                    Author   = "Stefano",
                    Subject  = "Custom stamp"
                };

                // Define the standard stamps template path!

                /*
                 * NOTE: The PDF specification defines several stamps (aka "standard stamps") whose rendering
                 * depends on the support of viewer applications. As such support isn't guaranteed, PDF Clown
                 * offers smooth, ready-to-use embedding of these stamps through the StampPath property of the
                 * document configuration: you can decide to point to the stamps directory of your Acrobat
                 * installation (e.g., in my GNU/Linux system it's located in
                 * "/opt/Adobe/Reader9/Reader/intellinux/plug_ins/Annotations/Stamps/ENU") or to the
                 * collection included in this distribution (std-stamps.pdf).
                 */
                document.Configuration.StampPath = GetResourcePath("../../pkg/templates/std-stamps.pdf");

                // Add a standard stamp, rotating it 15 degrees counterclockwise!
                new Stamp(
                    page,
                    new SKPoint(485, 515),
                    null, // Default size is natural size.
                    "This is 'Confidential', a standard stamp",
                    StandardStampEnum.Confidential)
                {
                    Rotation = 15,
                    Author   = "Stefano",
                    Subject  = "Standard stamp"
                };

                // Add a standard stamp, without rotation!
                new Stamp(
                    page,
                    new SKPoint(485, 580),
                    null, // Default size is natural size.
                    "This is 'SBApproved', a standard stamp",
                    StandardStampEnum.BusinessApproved)
                {
                    Author  = "Stefano",
                    Subject = "Standard stamp"
                };

                // Add a standard stamp, rotating it 10 degrees clockwise!
                new Stamp(
                    page,
                    new SKPoint(485, 635),
                    new SKSize(0, 40), // This scales the width proportionally to the 40-unit height (you can obviously do also the opposite, defining only the width).
                    "This is 'SHSignHere', a standard stamp",
                    StandardStampEnum.SignHere)
                {
                    Rotation = -10,
                    Author   = "Stefano",
                    Subject  = "Standard stamp"
                };
            }

            composer.ShowText("Text markup annotations:", new SKPoint(35, 650));
            {
                composer.BeginLocalState();
                composer.SetFont(font, 8);

                new TextMarkup(
                    page,
                    composer.ShowText("Highlight annotation", new SKPoint(35, 680)),
                    "Text of the Highlight annotation",
                    TextMarkup.MarkupTypeEnum.Highlight)
                {
                    Author  = "Stefano",
                    Subject = "An highlight text markup!"
                };
                new TextMarkup(
                    page,
                    composer.ShowText("Highlight annotation 2", new SKPoint(35, 695)).Inflate(0, 1),
                    "Text of the Highlight annotation 2",
                    TextMarkup.MarkupTypeEnum.Highlight)
                {
                    Color = DeviceRGBColor.Get(SKColors.Magenta)
                };
                new TextMarkup(
                    page,
                    composer.ShowText("Highlight annotation 3", new SKPoint(35, 710)).Inflate(0, 2),
                    "Text of the Highlight annotation 3",
                    TextMarkup.MarkupTypeEnum.Highlight)
                {
                    Color = DeviceRGBColor.Get(SKColors.Red)
                };

                new TextMarkup(
                    page,
                    composer.ShowText("Squiggly annotation", new SKPoint(180, 680)),
                    "Text of the Squiggly annotation",
                    TextMarkup.MarkupTypeEnum.Squiggly);
                new TextMarkup(
                    page,
                    composer.ShowText("Squiggly annotation 2", new SKPoint(180, 695)).Inflate(0, 2.5f),
                    "Text of the Squiggly annotation 2",
                    TextMarkup.MarkupTypeEnum.Squiggly)
                {
                    Color = DeviceRGBColor.Get(SKColors.Orange)
                };
                new TextMarkup(
                    page,
                    composer.ShowText("Squiggly annotation 3", new SKPoint(180, 710)).Inflate(0, 3),
                    "Text of the Squiggly annotation 3",
                    TextMarkup.MarkupTypeEnum.Squiggly)
                {
                    Color = DeviceRGBColor.Get(SKColors.Pink)
                };

                new TextMarkup(
                    page,
                    composer.ShowText("Underline annotation", new SKPoint(320, 680)),
                    "Text of the Underline annotation",
                    TextMarkup.MarkupTypeEnum.Underline
                    );
                new TextMarkup(
                    page,
                    composer.ShowText("Underline annotation 2", new SKPoint(320, 695)).Inflate(0, 2.5f),
                    "Text of the Underline annotation 2",
                    TextMarkup.MarkupTypeEnum.Underline
                    )
                {
                    Color = DeviceRGBColor.Get(SKColors.Orange)
                };
                new TextMarkup(
                    page,
                    composer.ShowText("Underline annotation 3", new SKPoint(320, 710)).Inflate(0, 3),
                    "Text of the Underline annotation 3",
                    TextMarkup.MarkupTypeEnum.Underline
                    )
                {
                    Color = DeviceRGBColor.Get(SKColors.Green)
                };

                new TextMarkup(
                    page,
                    composer.ShowText("StrikeOut annotation", new SKPoint(455, 680)),
                    "Text of the StrikeOut annotation",
                    TextMarkup.MarkupTypeEnum.StrikeOut
                    );
                new TextMarkup(
                    page,
                    composer.ShowText("StrikeOut annotation 2", new SKPoint(455, 695)).Inflate(0, 2.5f),
                    "Text of the StrikeOut annotation 2",
                    TextMarkup.MarkupTypeEnum.StrikeOut
                    )
                {
                    Color = DeviceRGBColor.Get(SKColors.Orange)
                };
                new TextMarkup(
                    page,
                    composer.ShowText("StrikeOut annotation 3", new SKPoint(455, 710)).Inflate(0, 3),
                    "Text of the StrikeOut annotation 3",
                    TextMarkup.MarkupTypeEnum.StrikeOut
                    )
                {
                    Color = DeviceRGBColor.Get(SKColors.Green)
                };

                composer.End();
            }
            composer.Flush();
        }
Пример #16
0
 public Ellipse(SKPoint center, float radius) : this()
 {
     Bounds = SKRect.Create(center.X - radius, center.Y - radius, radius * 2, radius * 2);
 }
Пример #17
0
        private void Apply(
            ListBox field
            )
        {
            Document document = field.Document;
            Widget   widget   = field.Widgets[0];

            Appearance appearance = widget.Appearance;
            {
                PdfDictionary widgetDataObject = widget.BaseDataObject;
                widgetDataObject[PdfName.DA] = new PdfString("/Helv " + FontSize + " Tf 0 0 0 rg");
                widgetDataObject[PdfName.MK] = new PdfDictionary(
                    new PdfName[]
                {
                    PdfName.BG,
                    PdfName.BC
                },
                    new PdfDirectObject[]
                {
                    new PdfArray(new PdfDirectObject[] { PdfReal.Get(.9), PdfReal.Get(.9), PdfReal.Get(.9) }),
                    new PdfArray(new PdfDirectObject[] { PdfInteger.Default, PdfInteger.Default, PdfInteger.Default })
                }
                    );
            }

            FormXObject normalAppearanceState;

            {
                SKSize size = widget.Box.Size;
                normalAppearanceState = new FormXObject(document, size);
                PrimitiveComposer composer = new PrimitiveComposer(normalAppearanceState);

                float  lineWidth = 1;
                SKRect frame     = SKRect.Create(lineWidth / 2, lineWidth / 2, size.Width - lineWidth, size.Height - lineWidth);
                if (GraphicsVisibile)
                {
                    composer.BeginLocalState();
                    composer.SetLineWidth(lineWidth);
                    composer.SetFillColor(BackColor);
                    composer.SetStrokeColor(ForeColor);
                    composer.DrawRectangle(frame, 5);
                    composer.FillStroke();
                    composer.End();
                }

                composer.BeginLocalState();
                if (GraphicsVisibile)
                {
                    composer.DrawRectangle(frame, 5);
                    composer.Clip(); // Ensures that the visible content is clipped within the rounded frame.
                }
                composer.BeginMarkedContent(PdfName.Tx);
                composer.SetFont(
                    new StandardType1Font(
                        document,
                        StandardType1Font.FamilyEnum.Helvetica,
                        false,
                        false
                        ),
                    FontSize
                    );
                double y = 3;
                foreach (ChoiceItem item in field.Items)
                {
                    composer.ShowText(
                        item.Text,
                        new SKPoint(0, (float)y)
                        );
                    y += FontSize * 1.175;
                    if (y > size.Height)
                    {
                        break;
                    }
                }
                composer.End();
                composer.End();

                composer.Flush();
            }
            appearance.Normal[null] = normalAppearanceState;
        }
Пример #18
0
        public static SKImage CropSurfaceToImage(SKSurface skSurface, int imageCanvasSize, int destSize, SKPaint paint)
        {
            SKImage skImage  = null;
            var     srcImage = skSurface.Snapshot();

            using (var newSurface = SKSurface.Create(new SKImageInfo(destSize, destSize))) {
                newSurface.Canvas.DrawImage(srcImage, SKRect.Create(0, 0, destSize, destSize), SKRect.Create(0, 0, destSize, destSize), paint);
                newSurface.Canvas.Flush();
                skImage = newSurface.Snapshot();
            }
            return(skImage);
        }
Пример #19
0
 public override SKRect GetHitbox()
 {
     return(SKRect.Create(X - Width / 2, Y - Height / 2, Width, Height));
 }
Пример #20
0
        public static SKImage ScaleSurfaceToImage(SKSurface skSurface, int imageCanvasSize, int destSize, SKPaint paint)
        {
            SKImage skImage = null;
            var     canvas  = skSurface.Canvas;

            // scale
            if (destSize == imageCanvasSize)
            {
                skImage = skSurface.Snapshot();
            }
            else
            {
                // 先缩放;然后绘制到小图上面,即相当于Crop了
                canvas.Scale(1.0f * destSize / imageCanvasSize);
                var srcImage = skSurface.Snapshot();

                using (var newSurface = SKSurface.Create(new SKImageInfo(destSize, destSize))) {
                    newSurface.Canvas.DrawImage(srcImage, SKRect.Create(0, 0, imageCanvasSize, imageCanvasSize), SKRect.Create(0, 0, destSize, destSize), paint);
                    newSurface.Canvas.Flush();
                    skImage = newSurface.Snapshot();
                }
            } // scale
            return(skImage);
        }
Пример #21
0
        private void DrawSatelliteTexts(SKCanvas Canvas)
        {
            IsInvalidSatelliteTexts = false;
            //	周辺テキストの描画
            if (SatelliteTexts?.Any() ?? false)
            {
                if (!IsClearCanvas)
                {
                    //	背景をクリア
                    var AntialiasPieRadius = PieRadius + AntialiasMargin;
                    using (var paint = new SKPaint())
                    {
                        paint.IsAntialias = true;
                        paint.Color       = Color.White.ToSKColor();
                        paint.StrokeCap   = SKStrokeCap.Round;
                        using (var path = new SKPath())
                        {
                            path.MoveTo(CanvasRect.Right, CanvasRect.Top);
                            path.LineTo(Center.X, CanvasRect.Top);
                            path.LineTo(Center.X, Center.Y - AntialiasPieRadius);
                            path.ArcTo(SKRect.Create(Center.X - AntialiasPieRadius, Center.Y - AntialiasPieRadius, AntialiasPieRadius * 2.0f, AntialiasPieRadius * 2.0f), 0.0f + OriginAngle, 180.0f, false);
                            path.LineTo(Center.X, CanvasRect.Bottom);
                            path.LineTo(CanvasRect.Right, CanvasRect.Bottom);
                            path.LineTo(CanvasRect.Right, CanvasRect.Top);
                            path.Close();
                            Canvas.DrawPath(path, paint);
                        }
                        using (var path = new SKPath())
                        {
                            path.MoveTo(CanvasRect.Left, CanvasRect.Top);
                            path.LineTo(Center.X, CanvasRect.Top);
                            path.LineTo(Center.X, Center.Y - AntialiasPieRadius);
                            path.ArcTo(SKRect.Create(Center.X - AntialiasPieRadius, Center.Y - AntialiasPieRadius, AntialiasPieRadius * 2.0f, AntialiasPieRadius * 2.0f), 0.0f + OriginAngle, -180.0f, false);
                            path.LineTo(Center.X, CanvasRect.Bottom);
                            path.LineTo(CanvasRect.Left, CanvasRect.Bottom);
                            path.LineTo(CanvasRect.Left, CanvasRect.Top);
                            path.Close();
                            Canvas.DrawPath(path, paint);
                        }
                    }
                }

                foreach (var SatelliteText in SatelliteTexts)
                {
                    if (!String.IsNullOrWhiteSpace(SatelliteText.Text))
                    {
                        using (var paint = new SKPaint())
                        {
                            paint.IsAntialias = true;
                            paint.Color       = SatelliteText.Color.ToSKColor();
                            paint.StrokeCap   = SKStrokeCap.Round;
                            paint.TextSize    = FontSize * PhysicalPixelRate;
                            paint.TextAlign   = SKTextAlign.Center;
                            paint.Typeface    = Font;

                            var TextRadius = PieRadius + paint.TextSize;
                            var TextCenter = Center + AngleRadiusToPoint(SatelliteText.Angle + OriginAngle, TextRadius);

                            Canvas.DrawText
                            (
                                SatelliteText.Text,
                                TextCenter.X,
                                TextCenter.Y + (paint.TextSize / 2.0f),
                                paint
                            );

                            paint.Typeface = null;
                        }
                    }
                }
            }
        }
Пример #22
0
 public override SKRect GetHitbox()
 {
     return(SKRect.Create(X, Y, Width, Height));;
 }
Пример #23
0
        protected override SKRect OnGetBounds()
        {
            BoundsFireCount++;

            return(SKRect.Create(100, 100));
        }
Пример #24
0
 public override void LayoutSubviews()
 {
     base.LayoutSubviews();
     _skView.Frame = SKRect.Create(SKPoint.Empty, ToPlatform(new SKSize((float)Bounds.Size.Width, (float)Bounds.Size.Height)));
 }
Пример #25
0
        protected override void OnDrawSample(SKCanvas canvas, int width, int height)
        {
            var modes = Enum.GetValues(typeof(SKXferMode)).Cast <SKXferMode>().ToArray();

            var cols = width < height ? 3 : 5;
            var rows = (modes.Length - 1) / cols + 1;

            var w         = (float)width / cols;
            var h         = (float)height / rows;
            var rect      = SKRect.Create(w, h);
            var srcPoints = new[] {
                new SKPoint(0.0f, 0.0f),
                new SKPoint(w, 0.0f)
            };
            var srcColors = new[] {
                SKColors.Magenta.WithAlpha(0),
                SKColors.Magenta
            };
            var dstPoints = new[] {
                new SKPoint(0.0f, 0.0f),
                new SKPoint(0.0f, h)
            };
            var dstColors = new[] {
                SKColors.Cyan.WithAlpha(0),
                SKColors.Cyan
            };

            using (var text = new SKPaint())
                using (var stroke = new SKPaint())
                    using (var src = new SKPaint())
                        using (var dst = new SKPaint())
                            using (var srcShader = SKShader.CreateLinearGradient(srcPoints[0], srcPoints[1], srcColors, null, SKShaderTileMode.Clamp))
                                using (var dstShader = SKShader.CreateLinearGradient(dstPoints[0], dstPoints[1], dstColors, null, SKShaderTileMode.Clamp))
                                {
                                    text.TextSize    = 12.0f;
                                    text.IsAntialias = true;
                                    text.TextAlign   = SKTextAlign.Center;
                                    stroke.IsStroke  = true;
                                    src.Shader       = srcShader;
                                    dst.Shader       = dstShader;

                                    canvas.Clear(SKColors.White);

                                    for (var i = 0; i < modes.Length; ++i)
                                    {
                                        using (new SKAutoCanvasRestore(canvas, true))
                                        {
                                            canvas.Translate(w * (i / rows), h * (i % rows));

                                            canvas.ClipRect(rect);
                                            canvas.DrawColor(SKColors.LightGray);

                                            canvas.SaveLayer(null);
                                            canvas.Clear(SKColors.Transparent);
                                            canvas.DrawPaint(dst);

                                            src.XferMode = modes[i];
                                            canvas.DrawPaint(src);
                                            canvas.DrawRect(rect, stroke);

                                            var desc = modes[i].ToString();
                                            canvas.DrawText(desc, w / 2f, h / 2f, text);
                                        }
                                    }
                                }
        }
Пример #26
0
 private void canvasView_Moved(SKPoint mousePoint)
 {
     if (leftPress)
     {
         if (cX > mousePoint.X)
         {
             newCX           = cX - mousePoint.X;
             rectangle2.Left = rleft - newCX;
         }
         else
         {
             newCX           = mousePoint.X - cX;
             rectangle2.Left = rleft + newCX;
         }
         if (cY > mousePoint.Y)
         {
             newCY          = cY - mousePoint.Y;
             rectangle2.Top = rtop - newCY;
         }
         else
         {
             newCY          = mousePoint.Y - cY;
             rectangle2.Top = rtop + newCY;
         }
     }
     if (bottomPress)
     {
         if (cX > mousePoint.X)
         {
             newCX            = cX - mousePoint.X;
             rectangle2.Right = rright - newCX;
         }
         else
         {
             newCX            = mousePoint.X - cX;
             rectangle2.Right = rright + newCX;
         }
         if (cY > mousePoint.Y)
         {
             newCY             = cY - mousePoint.Y;
             rectangle2.Bottom = rbottom - newCY;
         }
         else
         {
             newCY             = mousePoint.Y - cY;
             rectangle2.Bottom = rbottom + newCY;
         }
     }
     if (rightPress)
     {
         if (cX > mousePoint.X)
         {
             newCX            = cX - mousePoint.X;
             rectangle2.Right = rright - newCX;
         }
         else
         {
             newCX            = mousePoint.X - cX;
             rectangle2.Right = rright + newCX;
         }
         if (cY > mousePoint.Y)
         {
             newCY          = cY - mousePoint.Y;
             rectangle2.Top = rtop - newCY;
         }
         else
         {
             newCY          = mousePoint.Y - cY;
             rectangle2.Top = rtop + newCY;
         }
     }
     if (topPress)
     {
         if (cX > mousePoint.X)
         {
             newCX           = cX - mousePoint.X;
             rectangle2.Left = rleft - newCX;
         }
         else
         {
             newCX           = mousePoint.X - cX;
             rectangle2.Left = rleft + newCX;
         }
         if (cY > mousePoint.Y)
         {
             newCY             = cY - mousePoint.Y;
             rectangle2.Bottom = rbottom - newCY;
         }
         else
         {
             newCY             = mousePoint.Y - cY;
             rectangle2.Bottom = rbottom + newCY;
         }
     }
     if (onMove)
     {
         if (cX > mousePoint.X)
         {
             newCX            = cX - mousePoint.X;
             rectangle2.Left  = rleft - newCX;
             rectangle2.Right = rright - newCX;
         }
         else
         {
             newCX            = mousePoint.X - cX;
             rectangle2.Left  = rleft + newCX;
             rectangle2.Right = rright + newCX;
         }
         if (cY > mousePoint.Y)
         {
             newCY             = cY - mousePoint.Y;
             rectangle2.Bottom = rbottom - newCY;
             rectangle2.Top    = rtop - newCY;
         }
         else
         {
             newCY             = mousePoint.Y - cY;
             rectangle2.Bottom = rbottom + newCY;
             rectangle2.Top    = rtop + newCY;
         }
     }
     squareleft   = SKRect.Create(rectangle2.Left + 5, rectangle2.Top + 5, 40, 40);
     squareright  = SKRect.Create(rectangle2.Right - 45, rectangle2.Bottom - 45, 40, 40);
     squaretop    = SKRect.Create(rectangle2.Right - 45, rectangle2.Top + 5, 40, 40);
     squarebottom = SKRect.Create(rectangle2.Left + 5, rectangle2.Bottom - 45, 40, 40);
     canvasView.InvalidateSurface();
 }
Пример #27
0
 public void FillRect(float left, float top, float width, float height) =>
 Canvas.DrawRect(
     SKRect.Create(left, top, width, height), StyledPaint(PaintStyle.Fill));
Пример #28
0
        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(string.Format("Skia unable to read image {0}", 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);
        }
Пример #29
0
        private void DrawLegend(SKCanvas canvas, int width, int height)
        {
            if (!LegendNames.Any())
            {
                return;
            }

            List <SKColor> colors = new List <SKColor> {
            };

            foreach (List <ChartEntry> l in MultiBarEntries)
            {
                colors.Add(l[0].Color);
            }

            int rectWidth = 20;

            using (var paint = new SKPaint())
            {
                paint.TextSize    = this.LabelTextSize;
                paint.IsAntialias = true;
                paint.IsStroke    = false;

                float x = 200 + rectWidth * 2;
                float y = 50;

                foreach (string legend in LegendNames)
                {
                    paint.Color = SKColor.Parse("#000000");
                    canvas.DrawText(legend, x + rectWidth + 10, y, paint);

                    paint.Color = colors.ElementAt(LegendNames.IndexOf(legend));
                    var rect = SKRect.Create(x, y - rectWidth, rectWidth, rectWidth);
                    canvas.DrawRect(rect, paint);

                    x += rectWidth * 2 + this.LabelTextSize * (legend.Length / 2 + 2);
                }

                var minPoint = points.Min(p => p.Y);
                var maxPoint = points.Max(p => p.Y);

                paint.Color    = SKColor.Parse("#000000");
                paint.TextSize = 20;
                canvas.DrawCircle(12, minPoint, 5, paint);
                canvas.DrawText(NumbersTools.GetNember(multilineMax), 0, minPoint - 20, paint);
                canvas.DrawCircle(12, maxPoint, 5, paint);
                canvas.DrawText(NumbersTools.GetNember(multilineMin), 0, maxPoint - 20, paint);

                var step      = maxPoint / 4;
                var valueStep = multilineMax / 4;
                for (int i = 1; i < 4; i++)
                {
                    var tt = (maxPoint - step * i);
                    if (minPoint < (maxPoint - step * i) && Math.Abs(minPoint - (maxPoint - step * i)) >= step)
                    {
                        canvas.DrawCircle(12, (maxPoint - step * i), 5, paint);
                        canvas.DrawText(NumbersTools.GetNember(valueStep * i), 0, (maxPoint - step * i) - 20, paint);
                    }
                }
            }
        }
Пример #30
0
 public void Save(Stream stream, PageContainerViewModel container)
 {
     using var wstream = new SKManagedWStream(stream);
     using var canvas  = SKSvgCanvas.Create(SKRect.Create(0, 0, (int)container.Template.Width, (int)container.Template.Height), stream);
     _presenter.Render(canvas, _renderer, null, container, 0, 0);
 }