I'm developing an UWP app using Win2D and I want to know how to load an .svg file(present in my application) in Win2D. I don't know how to read the svg file and convert it into RandomAccessStream.
1 Answer
How to load an svg image in win2d (CanvasVirtualControl) using c#?
Win2D contains CanvasSvgDocument class that use to load svg from stream. You could StorageFile OpenReadAsync method to open svg file as stream then call CanvasSvgDocument.LoadAsync method to get svgDocument. For more please refer the the following.
CanvasVirtualControl canvasVirtualControl;
private void Page_Loaded(object sender, RoutedEventArgs e)
{
canvasVirtualControl = new CanvasVirtualControl();
canvasVirtualControl.Width = 1486;
canvasVirtualControl.Height = 610;
MyCanvas.Children.Add(canvasVirtualControl);
Canvas.SetLeft(canvasVirtualControl, 0);
Canvas.SetTop(canvasVirtualControl, 100);
canvasVirtualControl.RegionsInvalidated += CanvasVirtualControl_RegionsInvalidated;
}
private async void CanvasVirtualControl_RegionsInvalidated(CanvasVirtualControl sender, CanvasRegionsInvalidatedEventArgs args)
{
CanvasDrawingSession drawingSession;
Rect rect = new Rect(args.InvalidatedRegions[0].Left, args.InvalidatedRegions[0].Top, args.InvalidatedRegions[0].Width, args.InvalidatedRegions[0].Height);
using (drawingSession = sender.CreateDrawingSession(rect))
{
var file = await StorageFile.GetFileFromApplicationUriAsync(new Uri("ms-appx:///Assets/xxx.svg"));
using (var stream = await file.OpenReadAsync())
{
var svgDocument = await CanvasSvgDocument.LoadAsync(sender, stream);
drawingSession.DrawSvg(svgDocument, sender.Size);
}
}
}
8 Comments
Deepak Ganesan
Thanks a lot for your solution. I worked for me. But I have one more question, how to edit the attributes in the svg file (xml format) using the stream object
Nico Zhu
Please check
CanvasSvgDocument document to find FindElementById method. you could use it to get CanvasSvgNamedElement then edit matched attributeDeepak Ganesan
Hi bro, in my .svg there is no "id" attribute so how can I get the element without an id? Below one is my .svg file and I want to change the "fill" attribute present inside <path> element. <svg xmlns="w3.org/2000/svg" width="18" height="17" viewBox="0 0 18 17"> <g fill="none" fill-rule="evenodd" transform="translate(.492 .27)"> <path fill="#000000" d="M16.8477376,7.20815969 C16.8477376,6.35482636 16.1544043,5.66149302 15.3028487> </path> </g> </svg>
Nico Zhu
Please try use
LoadElementAsync to get element.Deepak Ganesan
Thank you so much for the reply. You saved me a lot of time. I found more specific answer [stackoverflow.com/questions/63500209/…
|