Beispiel #1
0
        private void canvas_CreateResources(Microsoft.Graphics.Canvas.UI.Xaml.CanvasControl sender, Microsoft.Graphics.Canvas.UI.CanvasCreateResourcesEventArgs args)
        //Yet more boilerplate code, this runs before canvas_Draw and is meant to be used to load any assets that need to be loaded from files
        {
            Board       = LoadAsset(sender, "Chess Board"); //These are all basically identical; they set the value of each variable to whatever LoadAsset returns given the file name.
            PawnBlack   = LoadAsset(sender, "PawnBlack");
            PawnWhite   = LoadAsset(sender, "PawnWhite");
            KnightBlack = LoadAsset(sender, "KnightBlack");
            KnightWhite = LoadAsset(sender, "KnightWhite");
            BishopBlack = LoadAsset(sender, "BishopBlack");
            BishopWhite = LoadAsset(sender, "BishopWhite");
            RookBlack   = LoadAsset(sender, "RookBlack");
            RookWhite   = LoadAsset(sender, "RookWhite");
            QueenBlack  = LoadAsset(sender, "QueenBlack");
            QueenWhite  = LoadAsset(sender, "QueenWhite");
            KingBlack   = LoadAsset(sender, "KingBlack");
            KingWhite   = LoadAsset(sender, "KingWhite");

            PlaceholderBlack = CanvasSvgDocument.LoadFromXml(sender, PawnBlack.GetXml().Replace("opacity=\"1\"", "opacity=\"0.5\""));
            PlaceholderWhite = CanvasSvgDocument.LoadFromXml(sender, PawnWhite.GetXml().Replace("opacity=\"1\"", "opacity=\"0.5\""));

            translator = new RenderTranslator(PawnBlack, PawnWhite, KnightBlack, KnightWhite, BishopBlack, BishopWhite, RookBlack, RookWhite, QueenBlack, QueenWhite, KingBlack, KingWhite, PlaceholderBlack, PlaceholderWhite);
            pieceSize  = new Size(sender.Size.Width / 16, sender.Size.Height / 16);

            pawn            = new Pawn(new Position(3, 3), true);
            MoveHighlight   = new Color();
            MoveHighlight.A = 100;
            MoveHighlight.R = 255;
            MoveHighlight.G = 255;
            MoveHighlight.B = 255;
        }
Beispiel #2
0
        private async Task RenderSvg(IRandomAccessStream writeStream)
        {
            var sharedDevice = CanvasDevice.GetSharedDevice();

            using (var offscreen = new CanvasRenderTarget(sharedDevice, (float)InkControl.RenderSize.Width, (float)InkControl.RenderSize.Height, 96))
            {
                using (var session = offscreen.CreateDrawingSession())
                {
                    var svgDocument = new CanvasSvgDocument(sharedDevice);

                    svgDocument.Root.SetStringAttribute("viewBox", $"0 0 {InkControl.RenderSize.Width} {InkControl.RenderSize.Height}");

                    foreach (var stroke in InkControl.InkPresenter.StrokeContainer.GetStrokes())
                    {
                        var canvasGeometry = CanvasGeometry.CreateInk(session, new[] { stroke }).Outline(); //.Simplify(CanvasGeometrySimplification.Lines);

                        var pathReceiver = new CanvasGeometryToSvgPathReader();
                        canvasGeometry.SendPathTo(pathReceiver);

                        var element = svgDocument.Root.CreateAndAppendNamedChildElement("path");

                        element.SetStringAttribute("d", pathReceiver.Path);

                        var color = stroke.DrawingAttributes.Color;

                        element.SetColorAttribute("fill", color);
                        //if (stroke.DrawingAttributes.DrawAsHighlighter)
                        //    element.SetFloatAttribute("fill-opacity", .9f);
                    }

                    await svgDocument.SaveAsync(writeStream);
                }
            }
        }
Beispiel #3
0
        public static Task WriteSvgAsync(CanvasSvgDocument document, IStorageFile file)
        {
            StringBuilder sb = new StringBuilder();

            sb.AppendLine("<!-- Exported by Character Map UWP -->");
            sb.Append(document.GetXml());
            return(FileIO.WriteTextAsync(file, sb.ToString()).AsTask());
        }
Beispiel #4
0
        private async void LoadSampleFile()
        {
            var file = await StorageFile.GetFileFromApplicationUriAsync(new Uri("ms-appx:///Assets/sample.svg"));

            using (var fileStream = await file.OpenReadAsync())
            {
                svgDocument = await CanvasSvgDocument.LoadAsync(canvasControl, fileStream);

                canvasControl.Invalidate();
            }
        }
Beispiel #5
0
        public SvgExample()
        {
            this.InitializeComponent();

            if (ThumbnailGenerator.IsDrawingThumbnail)
            {
                CurrentEffectType = EffectType.EdgeDetection;
            }

            svgSupported = CanvasSvgDocument.IsSupported(CanvasDevice.GetSharedDevice());

            if (!svgSupported)
            {
                optionsPanel.Visibility = Visibility.Collapsed;
            }
        }
Beispiel #6
0
        public static CanvasSvgDocument GenerateSvgDocument(
            ICanvasResourceCreator device,
            Rect rect,
            IList <string> paths,
            IList <Color> colors,
            bool invertBounds = true)
        {
            var           right  = Math.Ceiling(rect.Width);
            var           bottom = Math.Ceiling(rect.Height);
            StringBuilder sb     = new StringBuilder();

            sb.AppendFormat(
                CultureInfo.InvariantCulture,
                "<svg width=\"100%\" height=\"100%\" viewBox=\"{2} {3} {0} {1}\" xmlns=\"http://www.w3.org/2000/svg\">",
                right,
                bottom,
                invertBounds ? -Math.Floor(rect.Left) : Math.Floor(rect.Left),
                invertBounds ? -Math.Floor(rect.Top) : Math.Floor(rect.Top));

            foreach (var path in paths)
            {
                string p = path;
                if (path.StartsWith("F1 "))
                {
                    p = path.Remove(0, 3);
                }

                if (string.IsNullOrWhiteSpace(p))
                {
                    continue;
                }

                sb.AppendFormat("<path d=\"{0}\" style=\"fill: {1}; fill-opacity: {2}\" />",
                                p,
                                AsHex(colors[paths.IndexOf(path)]),
                                (double)colors[paths.IndexOf(path)].A / 255d);
            }
            sb.Append("</svg>");

            CanvasSvgDocument doc = CanvasSvgDocument.LoadFromXml(device, sb.ToString());

            // TODO : When we export colour SVGs we'll need to set all the correct path fills here

            return(doc);
        }
Beispiel #7
0
 internal Dictionary <byte, CanvasSvgDocument> map = new Dictionary <byte, CanvasSvgDocument>(); //Define a dictionary which maps bytes to Svg documents named map which can only be directly accessed through instances of this class
 public RenderTranslator(
     CanvasSvgDocument PawnBlack, CanvasSvgDocument PawnWhite, CanvasSvgDocument KnightBlack, CanvasSvgDocument KnightWhite, CanvasSvgDocument BishopBlack, CanvasSvgDocument BishopWhite, CanvasSvgDocument RookBlack, CanvasSvgDocument RookWhite, CanvasSvgDocument QueenBlack, CanvasSvgDocument QueenWhite, CanvasSvgDocument KingBlack, CanvasSvgDocument KingWhite, CanvasSvgDocument PlaceholderBlack, CanvasSvgDocument PlaceholderWhite)
 {
     map.Add(0b0001, PawnBlack);   //Map the RenderID of any given piece to the corresponding SVG object.
     map.Add(0b1001, PawnWhite);   //The way the encoding works is simple; it is the type of the piece, with 16 added if the piece is white.
     map.Add(0b0010, KnightBlack); //This means that in binary, the RenderID is 0 or 1 depending on the colour of the piece, followed by the piece's type ID in binary.
     map.Add(0b1010, KnightWhite); //The 0b prefix on an integer literal indicates that I want to work with the integer in binary.
     map.Add(0b0011, BishopBlack); //The reason for doing it this way is that the hashing for a byte is unbelievably fast, so the dictionary lookup will take so close to no time as to not make a difference.
     map.Add(0b1011, BishopWhite);
     map.Add(0b0100, RookBlack);
     map.Add(0b1100, RookWhite);
     map.Add(0b0101, QueenBlack);
     map.Add(0b1101, QueenWhite);
     map.Add(0b0110, KingBlack);
     map.Add(0b1110, KingWhite);
     map.Add(0b0111, PlaceholderBlack);
     map.Add(0b1111, PlaceholderWhite);
 }
Beispiel #8
0
        public async Task <WriteableBitmap> ToWriteableBitmap()
        {
            WriteableBitmap result = null;

            if (IsValid)
            {
                if (Source is WriteableBitmap)
                {
                    result = Source as WriteableBitmap;
                }
                else if (Source is BitmapSource)
                {
                    var bmp = Source as BitmapImage;
                    result = await bmp.ToWriteableBitmap();
                }
                else if (Source is SvgImageSource)
                {
                    var svg = Source as SvgImageSource;

                    if (Bytes is byte[])
                    {
                        CanvasDevice device      = CanvasDevice.GetSharedDevice();
                        var          svgDocument = new CanvasSvgDocument(device);
                        svgDocument = CanvasSvgDocument.LoadFromXml(device, Encoding.UTF8.GetString(Bytes));

                        using (var offscreen = new CanvasRenderTarget(device, (float)svg.RasterizePixelWidth, (float)svg.RasterizePixelHeight, 96))
                        {
                            var session = offscreen.CreateDrawingSession();
                            session.DrawSvg(svgDocument, new Size(Size, Size), 0, 0);
                            using (var imras = new InMemoryRandomAccessStream())
                            {
                                await offscreen.SaveAsync(imras, CanvasBitmapFileFormat.Png);

                                result = await imras.ToWriteableBitmap();
                            }
                        }
                    }
                }
            }
            return(result);
        }
Beispiel #9
0
        void CreateSomeSimplePlaceholderDocument()
        {
            svgDocument = new CanvasSvgDocument(canvasControl);

            {
                var rect = svgDocument.Root.CreateAndAppendNamedChildElement("rect");
                UseDefaultStroke(rect);
                rect.SetColorAttribute("fill", Color.FromArgb(0xFF, 0xFF, 0xFF, 0x0));
                rect.SetFloatAttribute("x", 20);
                rect.SetFloatAttribute("y", 20);
                rect.SetFloatAttribute("width", 100);
                rect.SetFloatAttribute("height", 100);
            }
            {
                var circle = svgDocument.Root.CreateAndAppendNamedChildElement("circle");
                UseDefaultStroke(circle);
                circle.SetColorAttribute("fill", Color.FromArgb(0xFF, 0x8B, 0x0, 0x0));
                circle.SetFloatAttribute("cx", 140);
                circle.SetFloatAttribute("cy", 140);
                circle.SetFloatAttribute("r", 70);
            }
            {
                var ellipse = svgDocument.Root.CreateAndAppendNamedChildElement("ellipse");
                UseDefaultStroke(ellipse);
                ellipse.SetColorAttribute("fill", Color.FromArgb(0xFF, 0x64, 0x95, 0xED));
                ellipse.SetFloatAttribute("cx", 200);
                ellipse.SetFloatAttribute("cy", 200);
                ellipse.SetFloatAttribute("rx", 150);
                ellipse.SetFloatAttribute("ry", 15);
            }
            {
                var line = svgDocument.Root.CreateAndAppendNamedChildElement("line");
                UseDefaultStroke(line);
                line.SetFloatAttribute("x1", 20);
                line.SetFloatAttribute("y1", 20);
                line.SetFloatAttribute("x2", 300);
                line.SetFloatAttribute("y2", 180);
            }
        }
Beispiel #10
0
        public static CanvasSvgDocument GenerateSvgDocument(
            ICanvasResourceCreator device,
            double width,
            double height,
            IList <SVGPathReciever> paths)
        {
            width  = Math.Ceiling(width);
            height = Math.Ceiling(height);
            StringBuilder sb = new StringBuilder();

            sb.AppendFormat("<svg width=\"100%\" height=\"100%\" viewBox=\"0 0 {0} {1}\" xmlns=\"http://www.w3.org/2000/svg\">", width, height);
            foreach (var receiver in paths)
            {
                sb.AppendFormat("<path d=\"{0}\" />", receiver.GetPathData());
            }
            sb.Append("</svg>");

            CanvasSvgDocument doc = CanvasSvgDocument.LoadFromXml(device, sb.ToString());

            // TODO : When we export colour SVGs we'll need to set all the correct path fills here

            return(doc);
        }
Beispiel #11
0
 public static Task WriteSvgAsync(CanvasSvgDocument document, IStorageFile file)
 {
     return(WriteSvgAsync(document.GetXml(), file));
 }
        public static async Task <ExportResult> ExportSvgAsync(
            ExportStyle style,
            InstalledFont selectedFont,
            FontVariant selectedVariant,
            Character selectedChar,
            CanvasTextLayoutAnalysis analysis,
            CanvasTypography typography)
        {
            try
            {
                string name = GetFileName(selectedFont, selectedVariant, selectedChar, "svg");
                if (await PickFileAsync(name, "SVG", new[] { ".svg" }) is StorageFile file)
                {
                    CachedFileManager.DeferUpdates(file);

                    CanvasDevice device    = Utils.CanvasDevice;
                    Color        textColor = style == ExportStyle.Black ? Colors.Black : Colors.White;


                    // If COLR format (e.g. Segoe UI Emoji), we have special export path.
                    if (style == ExportStyle.ColorGlyph && analysis.HasColorGlyphs && !analysis.GlyphFormats.Contains(GlyphImageFormat.Svg))
                    {
                        NativeInterop interop = Utils.GetInterop();
                        List <string> paths   = new List <string>();
                        Rect          bounds  = Rect.Empty;

                        foreach (var thing in analysis.Indicies)
                        {
                            var path = interop.GetPathDatas(selectedVariant.FontFace, thing.ToArray()).First();
                            paths.Add(path.Path);

                            if (!path.Bounds.IsEmpty)
                            {
                                var left   = Math.Min(bounds.Left, path.Bounds.Left);
                                var top    = Math.Min(bounds.Top, path.Bounds.Top);
                                var right  = Math.Max(bounds.Right, path.Bounds.Right);
                                var bottom = Math.Max(bounds.Bottom, path.Bounds.Bottom);
                                bounds = new Rect(
                                    left,
                                    top,
                                    right - left,
                                    bottom - top);
                            }
                        }

                        using (CanvasSvgDocument document = Utils.GenerateSvgDocument(device, bounds, paths, analysis.Colors, invertBounds: false))
                        {
                            await Utils.WriteSvgAsync(document, file);
                        }

                        return(new ExportResult(true, file));
                    }



                    var data = GetGeometry(1024, selectedVariant, selectedChar, analysis, typography);
                    async Task SaveMonochromeAsync()
                    {
                        using CanvasSvgDocument document = Utils.GenerateSvgDocument(device, data.Bounds, data.Path, textColor);
                        await Utils.WriteSvgAsync(document, file);
                    }

                    // If the font uses SVG glyphs, we can extract the raw SVG from the font file
                    if (analysis.GlyphFormats.Contains(GlyphImageFormat.Svg))
                    {
                        string  str = null;
                        IBuffer b   = GetGlyphBuffer(selectedVariant.FontFace, selectedChar.UnicodeIndex, GlyphImageFormat.Svg);
                        if (b.Length > 2 && b.GetByte(0) == 31 && b.GetByte(1) == 139)
                        {
                            using var stream = b.AsStream();
                            using var gzip   = new GZipStream(stream, CompressionMode.Decompress);
                            using var reader = new StreamReader(gzip);
                            str = reader.ReadToEnd();
                        }
                        else
                        {
                            using var dataReader       = DataReader.FromBuffer(b);
                            dataReader.UnicodeEncoding = Windows.Storage.Streams.UnicodeEncoding.Utf8;
                            str = dataReader.ReadString(b.Length);
                        }

                        if (str.StartsWith("<?xml"))
                        {
                            str = str.Remove(0, str.IndexOf(">") + 1);
                        }

                        str = str.TrimStart();

                        try
                        {
                            using (CanvasSvgDocument document = CanvasSvgDocument.LoadFromXml(Utils.CanvasDevice, str))
                            {
                                // We need to transform the SVG to fit within the default document bounds, as characters
                                // are based *above* the base origin of (0,0) as (0,0) is the Baseline (bottom left) position for a character,
                                // so by default a will appear out of bounds of the default SVG viewport (towards top left).

                                //if (!document.Root.IsAttributeSpecified("viewBox")) // Specified viewbox requires baseline transform?
                                {
                                    // We'll regroup all the elements inside a "g" / group tag,
                                    // and apply a transform to the "g" tag to try and put in
                                    // in the correct place. There's probably a more accurate way
                                    // to do this by directly setting the root viewBox, if anyone
                                    // can find the correct calculation...

                                    List <ICanvasSvgElement> elements = new List <ICanvasSvgElement>();

                                    double minTop    = 0;
                                    double minLeft   = double.MaxValue;
                                    double maxWidth  = double.MinValue;
                                    double maxHeight = double.MinValue;

                                    void ProcessChildren(CanvasSvgNamedElement root)
                                    {
                                        CanvasSvgNamedElement ele = root.FirstChild as CanvasSvgNamedElement;

                                        while (true)
                                        {
                                            CanvasSvgNamedElement next = root.GetNextSibling(ele) as CanvasSvgNamedElement;
                                            if (ele.Tag == "g")
                                            {
                                                ProcessChildren(ele);
                                            }
                                            else if (ele.Tag == "path")
                                            {
                                                // Create a XAML geometry to try and find the bounds of each character
                                                // Probably more efficient to do in Win2D, but far less code to do with XAML.
                                                Geometry gm = XamlBindingHelper.ConvertValue(typeof(Geometry), ele.GetStringAttribute("d")) as Geometry;
                                                minTop    = Math.Min(minTop, gm.Bounds.Top);
                                                minLeft   = Math.Min(minLeft, gm.Bounds.Left);
                                                maxWidth  = Math.Max(maxWidth, gm.Bounds.Width);
                                                maxHeight = Math.Max(maxHeight, gm.Bounds.Height);
                                            }
                                            ele = next;
                                            if (ele == null)
                                            {
                                                break;
                                            }
                                        }
                                    }

                                    ProcessChildren(document.Root);

                                    double top  = minTop < 0 ? minTop : 0;
                                    double left = minLeft;
                                    document.Root.SetRectangleAttribute("viewBox", new Rect(left, top, data.Bounds.Width, data.Bounds.Height));
                                }

                                await Utils.WriteSvgAsync(document, file);
                            }
                        }
                        catch
                        {
                            // Certain fonts seem to have their SVG glyphs encoded with... I don't even know what encoding.
                            // for example: https://github.com/adobe-fonts/emojione-color
                            // In these cases, fallback to monochrome black
                            await SaveMonochromeAsync();
                        }
                    }
                    else
                    {
                        await SaveMonochromeAsync();
                    }

                    await CachedFileManager.CompleteUpdatesAsync(file);

                    return(new ExportResult(true, file));
                }
            }
            catch (Exception ex)
            {
                await SimpleIoc.Default.GetInstance <IDialogService>()
                .ShowMessageBox(ex.Message, Localization.Get("SaveImageError"));
            }

            return(new ExportResult(false, null));
        }
Beispiel #13
0
        private async void MainPage_Loaded(object sender, RoutedEventArgs e)
        {
            db = new MapTilesDatabase();
            db.InitFromResource(MapTilesDatabase.PolandCustomMapBase);

            //MAP
            map.MapTapped += Map_MapTapped;
            map.Center     = new Geopoint(new BasicGeoposition()
            {
                Longitude = 21.006114275336859, Latitude = 52.231777083350494, Altitude = 163.6815999513492
            });
            map.ZoomLevel = 16;

            InitMapRouter();


            Console.SetOut(new ControlWriter(textOutput));

            win2dCanvas.PointerWheelChanged += (s, args) =>
            {
                var point = args.GetCurrentPoint(win2dCanvas);
                //System.Diagnostics.Debug.WriteLine($"{point.Properties.MouseWheelDelta}");
                tileScale       += tileScale * (point.Properties.MouseWheelDelta * tileScaleFactor);
                tileScale        = Math.Max(0, Math.Min(10, tileScale));
                canvasScalePoint = new System.Numerics.Vector2((float)point.Position.X, (float)point.Position.Y);
                win2dCanvas.Invalidate();
            };

            win2dCanvas.PointerPressed += (s, args) =>
            {
                panWithPointer = true;
                if (args.GetCurrentPoint(null).Properties.IsRightButtonPressed)
                {
                    canvasOffset = new System.Numerics.Vector2(0, 0);
                    tileScale    = 1f;
                    win2dCanvas.Invalidate();
                }
            };

            win2dCanvas.PointerMoved += (s, args) =>
            {
                if (panWithPointer)
                {
                    var cp = args.GetCurrentPoint(null);
                    if (lastPoint == null)
                    {
                        lastPoint = cp;
                    }
                    canvasOffset = new System.Numerics.Vector2(canvasOffset.X + (float)(cp.Position.X - lastPoint.Position.X), canvasOffset.Y + (float)(cp.Position.Y - lastPoint.Position.Y));
                    lastPoint    = cp;
                    win2dCanvas.Invalidate();
                }
            };

            win2dCanvas.PointerReleased += (s, args) =>
            {
                panWithPointer = false;
                lastPoint      = null;
            };

            win2dCanvas.DpiScale = 1;

            icons = new Dictionary <string, CanvasSvgDocument>();
            StorageFolder appInstalledFolder = Windows.ApplicationModel.Package.Current.InstalledLocation;
            StorageFolder assets             = await appInstalledFolder.GetFolderAsync("Icons");

            var files = await assets.GetFilesAsync();

            foreach (var f in files)
            {
                var shortName = System.IO.Path.GetFileNameWithoutExtension(f.Name).Split(".").Last();
                using (var stream = await f.OpenAsync(FileAccessMode.Read)) {
                    CanvasSvgDocument svg = await CanvasSvgDocument.LoadAsync(win2dCanvas, stream);

                    icons.Add(shortName, svg);
                }
            }
            ;
        }
        public static async Task ExportSvgAsync(
            ExportStyle style,
            InstalledFont selectedFont,
            FontVariant selectedVariant,
            Character selectedChar,
            CanvasTypography typography)
        {
            try
            {
                string name = GetFileName(selectedFont, selectedVariant, selectedChar, "svg");
                if (await PickFileAsync(name, "SVG", new[] { ".svg" }) is StorageFile file)
                {
                    CachedFileManager.DeferUpdates(file);
                    var device = Utils.CanvasDevice;

                    var textColor = style == ExportStyle.Black ? Colors.Black : Colors.White;

                    /* SVG Exports render at fixed size - but a) they're vectors, and b) they're
                     * inside an auto-scaling viewport. So rendersize is *largely* pointless */
                    float canvasH = 1024f, canvasW = 1024f, fontSize = 1024f;

                    using (CanvasTextLayout layout = new CanvasTextLayout(device, $"{selectedChar.Char}", new CanvasTextFormat
                    {
                        FontSize = fontSize,
                        FontFamily = selectedVariant.Source,
                        FontStretch = selectedVariant.FontFace.Stretch,
                        FontWeight = selectedVariant.FontFace.Weight,
                        FontStyle = selectedVariant.FontFace.Style,
                        HorizontalAlignment = CanvasHorizontalAlignment.Center
                    }, canvasW, canvasH))
                    {
                        layout.SetTypography(0, 1, typography);

                        using (CanvasGeometry temp = CanvasGeometry.CreateText(layout))
                        {
                            var    b     = temp.ComputeBounds();
                            double scale = Math.Min(1, Math.Min(canvasW / b.Width, canvasH / b.Height));

                            Matrix3x2 transform =
                                Matrix3x2.CreateTranslation(new Vector2((float)-b.Left, (float)-b.Top))
                                * Matrix3x2.CreateScale(new Vector2((float)scale));

                            using (CanvasGeometry geom = temp.Transform(transform))
                            {
                                /*
                                 * Unfortunately this only constructs a monochrome path, if we want color
                                 * Win2D does not yet expose the neccessary API's to get the individual glyph
                                 * layers that make up a colour glyph.
                                 *
                                 * We'll need to handle this in C++/CX if we want to do this at some point.
                                 */

                                SVGPathReciever rc = new SVGPathReciever();
                                geom.SendPathTo(rc);

                                Rect bounds = geom.ComputeBounds();
                                using (CanvasSvgDocument document = Utils.GenerateSvgDocument(device, bounds.Width, bounds.Height, rc))
                                {
                                    ((CanvasSvgNamedElement)document.Root.FirstChild).SetColorAttribute("fill", textColor);
                                    await Utils.WriteSvgAsync(document, file);
                                }
                            }
                        }
                    }

                    await CachedFileManager.CompleteUpdatesAsync(file);
                }
            }
            catch (Exception ex)
            {
                await SimpleIoc.Default.GetInstance <IDialogService>()
                .ShowMessageBox(ex.Message, Localization.Get("SaveImageError"));
            }
        }
Beispiel #15
0
        public static CanvasSvgDocument LoadAsset(CanvasControl sender, string fileName) //I wrote this one to clean up the previously very messy code in canvas_CreatResources; it deals with the file handling so I don't need to worry about that for each individual asset
        {
            var file = File.ReadAllText($"Assets/{fileName}.svg");                       //File.ReadAllText simply reads the whole file as a string, the $ strings work exactly like python f-strings, and Assets/ is the path where the assets are kept

            return(CanvasSvgDocument.LoadFromXml(sender, file));                         //CanvasSvgDocument.LoadFromXml takes in a string which is a valid Svg file and loads it into whatever form Win2D needs
        }
Beispiel #16
0
        internal static void DrawIcon(Tile.Feature f, float scale, CanvasDrawingSession session, CanvasSvgDocument icon, Color black, Color darkGray)
        {
            float        iconSize = 0.001f;
            Queue <uint> q        = new Queue <uint>(f.Geometries);
            float        cx       = 0;
            float        cy       = 0;

            if (f.Type == Tile.GeomType.Point)
            {
                var cmd = DecodeCommand(q.Dequeue());
                cx += DecodeParameter(q.Dequeue()) * scale;
                cy += DecodeParameter(q.Dequeue()) * scale;
                var m = session.Transform;
                session.Transform = Matrix3x2.CreateScale(0.25f, new Vector2(cx, cy)) * Matrix3x2.CreateTranslation(-2, -2);
                session.DrawSvg(icon, new Windows.Foundation.Size(iconSize, iconSize), cx - iconSize / 2f, cy - iconSize / 2f);
                session.Transform = m;
                //session.DrawCircle(cx, cy, 0.1f, Colors.Red);
            }
        }
Beispiel #17
0
 private void Clear_Clicked(object sender, RoutedEventArgs e)
 {
     // Clears everything.
     svgDocument = new CanvasSvgDocument(canvasControl);
     canvasControl.Invalidate();
 }