internal static void ExportSvg(IToolContext context, string path, IContainerView containerView)
 {
     using var wstream = new SKFileWStream(path);
     using var canvas  = SKSvgCanvas.Create(SKRect.Create(0, 0, (int)containerView.Width, (int)containerView.Height), wstream);
     using var skiaContainerPresenter = new SkiaExportContainerPresenter(context, containerView);
     skiaContainerPresenter.Draw(canvas, containerView.Width, containerView.Height, 0, 0, 1.0, 1.0);
 }
Beispiel #2
0
        public string ConvertToSvgDocument(IToolContext context, IContainerView containerView)
        {
            using (var stream = new MemoryStream())
            {
                using (var wstream = new SKManagedWStream(stream))
                    using (var writer = new SKXmlStreamWriter(wstream))
                        using (var canvas = SKSvgCanvas.Create(SKRect.Create(0, 0, (int)containerView.Width, (int)containerView.Height), writer))
                        {
                            if (containerView.SelectionState?.Shapes?.Count > 0)
                            {
                                using (var skiaSelectedPresenter = new SkiaExportSelectedPresenter(context, containerView))
                                {
                                    skiaSelectedPresenter.Draw(canvas, containerView.Width, containerView.Height, 0, 0, 1.0, 1.0);
                                }
                            }
                            else
                            {
                                using (var skiaContainerPresenter = new SkiaExportContainerPresenter(context, containerView))
                                {
                                    skiaContainerPresenter.Draw(canvas, containerView.Width, containerView.Height, 0, 0, 1.0, 1.0);
                                }
                            }
                        }

                stream.Position = 0;
                using (var reader = new StreamReader(stream, Encoding.UTF8))
                {
                    var xml = reader.ReadToEnd();
                    return(FormatXml(xml));
                }
            }
        }
Beispiel #3
0
 /// <inheritdoc/>
 public void Save(Stream stream, IPageContainer container)
 {
     using var wstream = new SKManagedWStream(stream);
     using var writer  = new SKXmlStreamWriter(wstream);
     using var canvas  = SKSvgCanvas.Create(SKRect.Create(0, 0, (int)container.Width, (int)container.Height), writer);
     _presenter.Render(canvas, _renderer, container, 0, 0);
 }
 void Save(string path, XContainer container)
 {
     using (var stream = new SKFileWStream(path))
         using (var writer = new SKXmlStreamWriter(stream))
             using (var canvas = SKSvgCanvas.Create(SKRect.Create(0, 0, (int)container.Width, (int)container.Height), writer))
             {
                 _presenter.Render(canvas, _renderer, container, 0, 0);
             }
 }
Beispiel #5
0
    public static void Render(Control target, Size size, Stream stream, double dpi = 96, bool useDeferredRenderer = false)
    {
        using var managedWStream = new SKManagedWStream(stream);
        var bounds = SKRect.Create(new SKSize((float)size.Width, (float)size.Height));

        using var canvas = SKSvgCanvas.Create(bounds, managedWStream);
        target.Measure(size);
        target.Arrange(new Rect(size));
        CanvasRenderer.Render(target, canvas, dpi, useDeferredRenderer);
    }
Beispiel #6
0
        private void SaveButton_OnClicked(object sender, RoutedEventArgs e)
        {
            var width  = Canvas.CanvasSize.Width;
            var bounds = SKRect.Create(0, 0, width, width);

            using (var stream = new SKFileWStream(@"C:\Temp\grid.svg"))
                using (var writer = new SKXmlStreamWriter(stream))
                    using (var canvas = SKSvgCanvas.Create(bounds, writer))
                    {
                        _hexPainter.DrawGrid(_gol.Grid, canvas, _cellRadius);
                    }
        }
Beispiel #7
0
 public void Draw(ParameterModel p)
 {
     using (var stream = new SKFileWStream(p.OutputFile))
         using (var writer = new SKXmlStreamWriter(stream))
         {
             var badge  = this._BadgeFactory.GetBadge(p);
             var width  = this._BadgeService.GetWidth(badge);
             var bounds = new SKRect(0, 0, width, p.Height);
             using (var canvas = SKSvgCanvas.Create(bounds, writer))
             {
                 this._BadgeService.DrawBadge(canvas, badge);
             }
         }
 }
Beispiel #8
0
        public void SvgCanvasCreatesValidDrawing()
        {
            using (var stream = new MemoryStream())
            {
                // draw the SVG
                using (var skStream = new SKManagedWStream(stream, false))
                    using (var writer = new SKXmlStreamWriter(skStream))
                        using (var canvas = SKSvgCanvas.Create(SKRect.Create(200, 150), writer))
                        {
                            var rectPaint = new SKPaint {
                                Color = SKColors.Blue, Style = SKPaintStyle.Fill
                            };
                            canvas.DrawRect(SKRect.Create(50, 70, 100, 30), rectPaint);

                            var circlePaint = new SKPaint {
                                Color = SKColors.Red, Style = SKPaintStyle.Fill
                            };
                            canvas.DrawOval(SKRect.Create(50, 70, 100, 30), circlePaint);

                            skStream.Flush();
                        }

                // reset the sream
                stream.Position = 0;

                // read the SVG
                var xdoc = XDocument.Load(stream);
                var svg  = xdoc.Root;

                var ns = (XNamespace)"http://www.w3.org/2000/svg";

                Assert.Equal(ns, svg.GetDefaultNamespace());
                Assert.Equal("200", svg.Attribute("width").Value);
                Assert.Equal("150", svg.Attribute("height").Value);

                var rect = svg.Element(ns + "rect");
                Assert.Equal("rgb(0,0,255)", rect.Attribute("fill").Value);
                Assert.Equal("50", rect.Attribute("x").Value);
                Assert.Equal("70", rect.Attribute("y").Value);
                Assert.Equal("100", rect.Attribute("width").Value);
                Assert.Equal("30", rect.Attribute("height").Value);

                var ellipse = svg.Element(ns + "ellipse");
                Assert.Equal("rgb(255,0,0)", ellipse.Attribute("fill").Value);
                Assert.Equal("100", ellipse.Attribute("cx").Value);
                Assert.Equal("85", ellipse.Attribute("cy").Value);
                Assert.Equal("50", ellipse.Attribute("rx").Value);
                Assert.Equal("15", ellipse.Attribute("ry").Value);
            }
        }
Beispiel #9
0
        public static bool ToSvg(this SKPicture skPicture, string path, SKColor background, float scaleX, float scaleY)
        {
            float width  = skPicture.CullRect.Width * scaleX;
            float height = skPicture.CullRect.Height * scaleY;

            if (width <= 0 || height <= 0)
            {
                return(false);
            }
            using var skFileWStream = new SKFileWStream(path);
            using var skCanvas      = SKSvgCanvas.Create(SKRect.Create(0, 0, width, height), skFileWStream);
            Draw(skPicture, background, scaleX, scaleY, skCanvas);
            return(true);
        }
Beispiel #10
0
        public static void Test(string outputDirectory)
        {
            int width  = 500;
            int height = 500;


            SKRect svgBounds = SKRect.Create(0, 0, 100, 100);

            outputDirectory = System.IO.Path.Combine(outputDirectory, "SkiaTestFile.svg");

            using (SKFileWStream stream = new SKFileWStream(outputDirectory)) // there are a few types of streams
            {
                using (SKCanvas canvas = SKSvgCanvas.Create(svgBounds, stream))

                // SKBitmap bitmap = new SKBitmap(width, height);
                // using (SKCanvas canvas = new SKCanvas(bitmap))
                {
                    using (SKPaint paint = new SKPaint())
                    {
                        paint.Typeface = SKTypeface.FromFamilyName(null, SKTypefaceStyle.Bold);
                        paint.TextSize = 10;

                        // paint.Style = SKPaintStyle.Stroke;
                        // paint.StrokeWidth = 1;
                        // paint.Color = SKColors.Red;

                        using (SKPath textPath = paint.GetTextPath("CODE", 0, 0))
                        {
                            // Set transform to center and enlarge clip path to window height
                            SKRect bounds;
                            textPath.GetTightBounds(out bounds);

                            // canvas.Translate(width / 2, height/ 2);
                            // canvas.Scale(width / bounds.Width, height / bounds.Height);
                            // canvas.Translate(-bounds.MidX, -bounds.MidY);

                            canvas.Translate(-bounds.Left, -bounds.Top);

                            // Set the clip path
                            // canvas.ClipPath(textPath);
                            canvas.DrawPath(textPath, paint);
                        } // End Using textPath
                    }     // End Using paint
                }         // End Using canvas
            }             // End Using stream

            // string foo = bitmap.ToString();
            //System.Console.WriteLine(foo);
            System.Console.WriteLine("text");
        }
Beispiel #11
0
        /// <inheritdoc/>
        public void Export(IPlotModel model, Stream stream)
        {
            using var skStream = new SKManagedWStream(stream);
            using var writer   = new SKXmlStreamWriter(skStream);
            using var canvas   = SKSvgCanvas.Create(new SKRect(0, 0, this.Width, this.Height), writer);

            if (!model.Background.IsInvisible())
            {
                canvas.Clear(model.Background.ToSKColor());
            }

            // SVG export does not work with UseTextShaping=true. However SVG does text shaping by itself anyway, so we can just disable it
            using var context = new SkiaRenderContext { RenderTarget = RenderTarget.VectorGraphic, SkCanvas = canvas, UseTextShaping = false };
            model.Update(true);
            model.Render(context, new OxyRect(0, 0, this.Width, this.Height));
        }
Beispiel #12
0
        public static byte[] RenderSvg(int size, VoxelData voxelData)
        {
            var ms = new MemoryStream();

            using (var skStream = new SKManagedWStream(ms)) {
                using (var writer = new SKXmlStreamWriter(skStream)) {
                    using (var canvas = SKSvgCanvas.Create(SKRect.Create(0, 0, size, size), writer)) {
                        RenderQuads(voxelData, size, canvas, new MeshSettings {
                            FrontFaces   = true,
                            FakeLighting = true,
                            MeshType     = MeshType.Quads,
                        });
                    }
                }
            }
            return(ms.ToArray());
        }
Beispiel #13
0
        private void UpdateSvg()
        {
            bool exportPresenter = _previewWindow.svgExport.IsChecked == true;
            bool showPrintable   = _previewWindow.svgPrintable.IsChecked == true;

            Task.Factory.StartNew(() =>
            {
                try
                {
                    IImageCache ic = _projectEditor.Project;
                    var container  = _projectEditor.Project.CurrentContainer;

                    var renderer = new SkiaSharpRenderer(true, 96.0);
                    if (!showPrintable)
                    {
                        renderer.State.DrawShapeState.Flags = ShapeStateFlags.Printable;
                    }
                    renderer.State.ImageCache = _projectEditor.Project;

                    var presenter = exportPresenter ? (ContainerPresenter) new ExportPresenter() : (ContainerPresenter) new EditorPresenter();

                    using (var ms = new MemoryStream())
                    {
                        using (var stream = new SKManagedWStream(ms))
                        {
                            using (var writer = new SKXmlStreamWriter(stream))
                                using (var canvas = SKSvgCanvas.Create(SKRect.Create(0, 0, (int)container.Width, (int)container.Height), writer))
                                {
                                    presenter.Render(canvas, renderer, container, 0, 0);
                                }
                            stream.Flush();
                        }

                        var svg = Encoding.ASCII.GetString(ms.GetBuffer(), 0, (int)ms.Length);

                        Dispatcher.Invoke(() =>
                        {
                            _previewWindow.svgText.Text = svg;
                        });
                    }
                }
                catch (Exception) { }
            });
        }
Beispiel #14
0
        public void SvgCanvasSavesFile()
        {
            var stream = new MemoryStream();

            using (var wstream = new SKManagedWStream(stream))
                using (var writer = new SKXmlStreamWriter(wstream))
                    using (var svg = SKSvgCanvas.Create(SKRect.Create(100, 100), writer))
                    {
                        var paint = new SKPaint
                        {
                            Color = SKColors.Red,
                            Style = SKPaintStyle.Fill
                        };
                        svg.DrawRect(SKRect.Create(10, 10, 80, 80), paint);
                    }

            stream.Position = 0;

            using (var reader = new StreamReader(stream))
            {
                var xml  = reader.ReadToEnd();
                var xdoc = XDocument.Parse(xml);

                var svg = xdoc.Root;
                var ns  = svg.Name.Namespace;

                Assert.Equal(ns + "svg", svg.Name);
                Assert.Equal("100", svg.Attribute("width")?.Value);
                Assert.Equal("100", svg.Attribute("height")?.Value);

                var rect = svg.Element(ns + "rect");
                Assert.Equal(ns + "rect", rect.Name);
                Assert.Equal("rgb(255,0,0)", rect.Attribute("fill")?.Value);
                Assert.Equal("none", rect.Attribute("stroke")?.Value);
                Assert.Equal("10", rect.Attribute("x")?.Value);
                Assert.Equal("10", rect.Attribute("y")?.Value);
                Assert.Equal("80", rect.Attribute("width")?.Value);
                Assert.Equal("80", rect.Attribute("height")?.Value);
            }
        }
    /// <inheritdoc/>
    public void Export(IPlotModel model, Stream stream)
    {
        using var skStream = new SKManagedWStream(stream);
        using var canvas   = SKSvgCanvas.Create(new SKRect(0, 0, Width, Height), skStream);

        if (!model.Background.IsInvisible())
        {
            canvas.Clear(model.Background.ToSKColor());
        }

        // SVG export does not work with UseTextShaping=true. However SVG does text shaping by itself anyway, so we can just disable it
        using var context = new SkiaRenderContext
              {
                  RenderTarget   = RenderTarget.VectorGraphic,
                  SkCanvas       = canvas,
                  UseTextShaping = false,
                  DpiScale       = Dpi / 96
              };
        //use fake dpi to scale, looks much better!
        model.Update(true);
        model.Render(context, new OxyRect(0, 0, Width / context.DpiScale, Height / context.DpiScale));
    }
Beispiel #16
0
        /// <summary>
        /// Creates an SVG image instead of a PNG file, but otherwise operates the same as DrawAreaAtSize.
        /// </summary>
        /// <param name="stats">the image properties to draw</param>
        /// <param name="drawnItems">the list of elements to draw. Will load from the database if null.</param>
        /// <param name="styles">a dictionary of TagParserEntries to select to draw</param>
        /// <param name="filterSmallAreas">if true, skips entries below a certain size when drawing.</param>
        /// <returns>a string containing the SVG XML</returns>
        public string DrawAreaAtSizeSVG(ImageStats stats, List <DbTables.Place> drawnItems = null, Dictionary <string, StyleEntry> styles = null, bool filterSmallAreas = true)
        {
            //TODO: make this take CompletePaintOps
            //This is the new core drawing function. Takes in an area, the items to draw, and the size of the image to draw.
            //The drawn items get their paint pulled from the TagParser's list. If I need multiple match lists, I'll need to make a way
            //to pick which list of tagparser rules to use.

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

            double minimumSize = 0;

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

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

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

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

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

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


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

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

                    break;

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

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

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

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

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

            return(svgData);
        }
Beispiel #17
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);
 }
Beispiel #18
0
        static void Main(string[] args)
        {
            // load some routing data and build a routing network.
            var routerDb = new RouterDb();

            using var stream = File.Open(@"C:\Users\yukik\Downloads\zuid-holland-latest.osm.pbf", FileMode.Open, FileAccess.Read);
            var src = new PBFOsmStreamSource(stream);

            routerDb.LoadOsmData(src, Vehicle.Bicycle); // create the network for Bicycle only.

            // create a router.
            var router = new Router(routerDb);

            // get a profile.
            var profile = Vehicle.Bicycle.Fastest(); // the default OSM Bicycle profile.

            // create a routerpoint from a location.
            // snaps the given location to the nearest routable edge.
            var start = router.Resolve(profile, 52.154820f, 4.479307f);
            var end   = router.Resolve(profile, 52.160942f, 4.495821f);

            // calculate a route.
            var route = router.Calculate(profile, start, end);

            var retList = new List <(float lat, float lon, float time, float distance, string name)>();


            // Create the path
            var path = new SKPath();

            var firstShape = route.Shape[0];

            path.MoveTo(5, 5);

            var strokePaint = new SKPaint
            {
                Style       = SKPaintStyle.Stroke,
                Color       = SKColors.Black,
                StrokeWidth = 1
            };

            int scale = 50000;

            for (int i = 1; i < route.ShapeMeta.Length - 2; i++)
            {
                var meta = route.ShapeMeta[i];

                var strn    = meta.Attributes.TryGetValue("name", out var desc);
                var current = route.Shape[meta.Shape];
                if (meta.Shape > 0 && route.ShapeMeta[i - 1].Attributes.TryGetValue("name", out var v) && v == desc)
                {
                    continue;
                }

                if (route.Shape.Length <= meta.Shape + 1)
                {
                    continue;
                }
                var lat = (current.Latitude - firstShape.Latitude) * scale;
                var lon = (current.Longitude - firstShape.Longitude) * scale;
                retList.Add((lat, lon, meta.Time - retList.LastOrDefault().time, meta.Distance - retList.LastOrDefault().distance, desc));

                path.LineTo(lon, -lat);
            }

            var rect = path.Bounds;
            var translationMatrix = SKMatrix.CreateTranslation(Math.Abs(path.Bounds.Left) + 20, Math.Abs(path.Bounds.Top) + 20);

            path.Transform(translationMatrix);
            rect.Inflate(100, 10);
            using var outStream = new SKDynamicMemoryWStream();
            var svg = SKSvgCanvas.Create(rect, outStream);


            svg.DrawPath(path, strokePaint);

            foreach (var(lat, lon, time, distance, name) in retList)
            {
                var point = new SKPoint(lon, -lat);

                svg.DrawText($"{name} ({TimeSpan.FromSeconds(time).Humanize()} - {Math.Round(distance)} meter) ", translationMatrix.MapPoint(point), strokePaint);
            }


            var s = outStream.DetachAsData();

            File.WriteAllBytes("test.svg", s.ToArray());

            Console.WriteLine("Hello World!");
        }