Esempio n. 1
0
        async void OnSourceChanged()
        {
            if (Source.Contains("http"))
            {
                using (Stream stream = await httpClient.GetStreamAsync(Source))
                {
                    using (MemoryStream memStream = new MemoryStream())
                    {
                        await stream.CopyToAsync(memStream);

                        memStream.Seek(0, SeekOrigin.Begin);
                        skSvg.Load(memStream);
                    }
                }
            }
            else
            {
                using (var memStream = LocalResource.GetStream(Source))
                {
                    memStream.Seek(0, SeekOrigin.Begin);
                    skSvg.Load(memStream);
                }
            }

            InvalidateSurface();
        }
Esempio n. 2
0
        public static SKSvg GetSvgImage(string source)
        {
            if (string.IsNullOrEmpty(source))
            {
                return(null);
            }
            var assembly = typeof(ImageResourceExtension).GetTypeInfo().Assembly;

            if (!source.StartsWith("com."))
            {
                source = "ChineseJourney.Common.Resources.svgs." + source;
            }
            if (!source.EndsWith(".svg"))
            {
                source += ".svg";
            }

            using (var stream = assembly.GetManifestResourceStream(source))
            {
                var svg = new SKSvg();
                if (stream != null)
                {
                    svg.Load(stream);
                }
                return(svg);
            }
        }
Esempio n. 3
0
        public async Task <SKSvg> LoadImageAsync(ImageSource imageSource,
                                                 CancellationToken cancellationToken = new CancellationToken())
        {
            SKSvg          loader = new SKSvg();
            UriImageSource source = imageSource as UriImageSource;
            HttpClient     client = new HttpClient();

            using (client)
            {
                HttpResponseMessage response = await client.GetAsync(source.Uri, cancellationToken)
                                               .ConfigureAwait(false);

                Stream stream = await response.Content.ReadAsStreamAsync()
                                .ConfigureAwait(false);

                using (stream)
                {
                    if (stream != null)
                    {
                        loader.Load(stream);
                    }
                }
            }

            return(loader);
        }
Esempio n. 4
0
        internal static SKSvg Load(string fileName)
        {
            var result = new SKSvg();

            using (var stream = File.OpenRead(fileName))
            {
                using (var reader = XmlReader.Create(stream, XmlReaderSettings, CreateSvgXmlContext()))
                {
                    var preloadSvg = XDocument.Load(reader);

                    var root = preloadSvg.Root;

                    // In order to avoid rounding errors, always create a 1024x1024 SVG from the input
                    var width  = root.Attribute("width");
                    var height = root.Attribute("height");

                    if (width.Value != "1024px" || height.Value != "1024px")
                    {
                        Log.Warning("For best result the source app icon should be 1024x1024");
                    }

                    width.Value  = "1024px";
                    height.Value = "1024px";

                    result.Load(preloadSvg.CreateReader());
                }
            }

            return(result);
        }
Esempio n. 5
0
        public static BitmapInfo LoadBitmap(object bitmapStream)
        {
            // todo: Our BitmapRegistry stores not only bitmaps. Perhaps we should store a class in it
            // which has all information. So we should have a SymbolImageRegistry in which we store a
            // SymbolImage. Which holds the type, data and other parameters.
            if (bitmapStream is Stream stream)
            {
                if (stream.IsSvg())
                {
                    var svg = new SKSvg();
                    svg.Load(stream);

                    return(new BitmapInfo {
                        Svg = svg
                    });
                }

                var image = SKImage.FromEncodedData(SKData.CreateCopy(stream.ToBytes()));
                return(new BitmapInfo {
                    Bitmap = image
                });
            }

            if (bitmapStream is Sprite sprite)
            {
                return(new BitmapInfo {
                    Sprite = sprite
                });
            }

            return(null);
        }
Esempio n. 6
0
        private void CanvasViewOnPaintSurface(object sender, SKPaintSurfaceEventArgs args)
        {
            SKCanvas canvas = args.Surface.Canvas;

            canvas.Clear();

            if (string.IsNullOrEmpty(SvgPath))
            {
                return;
            }

            using (Stream stream = SvgAssembly.GetManifestResourceStream(SvgPath))
            {
                SKSvg svg = new SKSvg();
                svg.Load(stream);

                SKImageInfo info = args.Info;
                canvas.Translate(info.Width / 2f, info.Height / 2f);

                SKRect bounds = svg.ViewBox;
                float  xRatio = info.Width / bounds.Width;
                float  yRatio = info.Height / bounds.Height;

                float ratio = Math.Min(xRatio, yRatio);

                canvas.Scale(ratio);
                canvas.Translate(-bounds.MidX, -bounds.MidY);

                canvas.DrawPicture(svg.Picture);
            }
        }
Esempio n. 7
0
        public void SvgLoadsDashes()
        {
            var path = Path.Combine(PathToImages, "dashes.svg");

            var svg = new SKSvg();

            svg.Load(path);

            var bmp    = new SKBitmap((int)svg.CanvasSize.Width, (int)svg.CanvasSize.Height);
            var canvas = new SKCanvas(bmp);

            canvas.Clear(SKColors.White);
            canvas.DrawPicture(svg.Picture);
            canvas.Flush();

            Assert.AreEqual(SKColors.Black, bmp.GetPixel(10 + 3, 20));
            Assert.AreEqual(SKColors.Black, bmp.GetPixel(10 + 7, 20));
            Assert.AreEqual(SKColors.White, bmp.GetPixel(10 + 13, 20));

            Assert.AreEqual(SKColors.Black, bmp.GetPixel(10 + 3, 40));
            Assert.AreEqual(SKColors.White, bmp.GetPixel(10 + 7, 40));
            Assert.AreEqual(SKColors.Black, bmp.GetPixel(10 + 13, 40));

            Assert.AreEqual(SKColors.White, bmp.GetPixel(10 + 3, 60));
            Assert.AreEqual(SKColors.Black, bmp.GetPixel(10 + 7, 60));
            Assert.AreEqual(SKColors.Black, bmp.GetPixel(10 + 13, 60));

            Assert.AreEqual(SKColors.Black, bmp.GetPixel(10 + 3, 80));
            Assert.AreEqual(SKColors.Black, bmp.GetPixel(10 + 7, 80));
            Assert.AreEqual(SKColors.White, bmp.GetPixel(10 + 13, 80));
        }
        public void SvgRespectsClipPath()
        {
            var path       = Path.Combine(PathToImages, "clipping.svg");
            var background = (SKColor)0xffffffff;
            var fill       = (SKColor)0xff000000;

            var svg = new SKSvg();

            svg.Load(path);

            var bmp    = new SKBitmap((int)svg.CanvasSize.Width, (int)svg.CanvasSize.Height);
            var canvas = new SKCanvas(bmp);

            canvas.Clear(background);

            canvas.DrawPicture(svg.Picture);
            canvas.Flush();

            for (int x = 1; x < 20; x++)
            {
                for (int y = 1; y < 20; y++)
                {
                    Assert.Equal(fill, bmp.GetPixel(x, y));
                    Assert.Equal(background, bmp.GetPixel(x + 20, y + 20));
                }
            }
        }
Esempio n. 9
0
        public static SKData EncodeSvg(FsPath svgFile, int maxWidht, int maxHeight, SKEncodedImageFormat format = SKEncodedImageFormat.Png)
        {
            var svg = new SKSvg();

            svg.Load(svgFile.ToString());

            if (svg.Picture == null)
            {
                return(SKData.Empty);
            }

            SKRect svgSize = svg.Picture.CullRect;

            (int renderWidth, int renderHeight, float scale)sizeData = CalcNewSize(svgSize, maxWidht, maxHeight);

            var matrix = SKMatrix.CreateScale(sizeData.scale, sizeData.scale);

            using (SKBitmap bitmap = new SKBitmap(sizeData.renderWidth, sizeData.renderHeight))
            {
                using (SKCanvas canvas = new SKCanvas(bitmap))
                {
                    canvas.DrawPicture(svg.Picture, ref matrix);
                    canvas.Flush();
                }

                using (SKImage image = SKImage.FromBitmap(bitmap))
                {
                    return(image.Encode(format, 100));
                }
            }
        }
        private static async Task GenerateAssets(string[] files, DeviceType mode, string destinationDirectory,
                                                 int quality, string postfix)
        {
            // It fails to create the first file
            var firstItem  = files[0];
            var initalLoad = new SKSvg();

            initalLoad.Load(firstItem);
            await PngHelper.GeneratePng((int)initalLoad.CanvasSize.Width, (int)initalLoad.CanvasSize.Height,
                                        firstItem, "temp", 1);

            File.Delete("temp");

            foreach (var filepath in files.OrderBy(s => s).ToList())
            {
                Console.WriteLine($"Creating assets from {filepath}");

                var filename = Path.GetFileNameWithoutExtension(filepath);
                if (mode == DeviceType.iOS)
                {
                    var generator = new IOSAssetGenerator();
                    await generator.CreateAsset(filepath, filename, destinationDirectory, quality, string.Empty);
                }
                else
                {
                    var generator = new AndroidAssetGenerator();
                    await generator.CreateAsset(filepath, filename, destinationDirectory, quality, postfix);
                }
            }
        }
Esempio n. 11
0
        public SKSvg GetSvgImage(string source, bool highlightRadical = false, int numStroke = -1)
        {
            if (string.IsNullOrEmpty(source))
            {
                return(null);
            }

            var zi = HanZi[source];

            string strokes = string.Empty;

            for (var index = 0; index < zi.strokes.Length && (numStroke < 0 || index <= numStroke); index++)
            {
                string color = "black";
                if (highlightRadical && (zi.radStrokes == null || zi.radStrokes.Contains(index)))
                {
                    color = "blue";
                }
                var ziStroke = zi.strokes[index];
                strokes += "<path d=\"" + ziStroke + "\" fill=\"" + color + "\"/>" + System.Environment.NewLine;
            }

            using (var stream = HanziSvgTemplate.Replace("STROKE_PATH", strokes).ToStream())
            {
                var svg = new SKSvg();
                svg.Load(stream);
                return(svg);
            }
        }
Esempio n. 12
0
        public void Load(Stream stream)
        {
            IsReady = false;

            _svg.Load(stream);

            IsReady = true;
        }
Esempio n. 13
0
        /// <summary>
        /// Loads image from filename
        /// </summary>
        /// <param name="filename">image filename</param>
        /// <returns>loaded SVG image object, or null when loading was not successful</returns>
        private static SKSvg LoadImageFromFile(string filename)
        {
            var svg = new SKSvg();

            svg.Load(filename);

            return(svg);
        }
Esempio n. 14
0
        protected override Task OnInit()
        {
            svg = new SKSvg();
            using (var stream = SampleMedia.Images.OpacitySvg)
                svg.Load(stream);

            return(base.OnInit());
        }
Esempio n. 15
0
        public static void CreateIcon(string sBgImg, string sFgImg, ref string icoOutput)
        {
            var ms = new MemoryStream();

            // If input is SVG, create PNG
            if (sBgImg.EndsWith(".svg"))
            {
                using var svg = new SKSvg();
                if (svg.Load(sBgImg) is { })
        public SKSvgElement(Stream resourceStream)
        {
            _svg        = new SKSvg();
            _skPicuture = _svg.Load(resourceStream);

            var bounds = _svg.Picture.CullRect;

            Limites = new Retangulo(bounds.Left, bounds.Top, bounds.Right, bounds.Bottom);
        }
Esempio n. 17
0
        public static SKPicture GetSvgData(string svgName)
        {
            SKSvg svg = new SKSvg();

            using (var stream = GetImageStream(svgName))
            {
                return(svg.Load(stream));
            }
        }
Esempio n. 18
0
        private void LoadSvg(string svgName)
        {
            // create a new SVG object
            svg = new SKSvg();

            // load the SVG document from a stream
            using var stream = GetImageStream(svgName);
            svg.Load(stream);
        }
Esempio n. 19
0
        private static SKBitmap LoadSvgBitmap(string svgPath, SKColor?background = null)
        {
            // open the SVG
            var svg = new SKSvg();

            svg.Load(svgPath);

            return(CreateBitmap(svg, background));
        }
Esempio n. 20
0
        public void LoadSvgCustomCanvasSize()
        {
            var path = Path.Combine(PathToImages, "logos.svg");

            var svg = new SKSvg(new SKSize(150, 150));

            svg.Load(path);

            Assert.Equal(new SKSize(150, 150), svg.CanvasSize);
        }
Esempio n. 21
0
        public void LoadSvgCanvasSize()
        {
            var path = Path.Combine(PathToImages, "logos.svg");

            var svg = new SKSvg();

            svg.Load(path);

            Assert.AreEqual(new SKSize(300, 300), svg.CanvasSize);
        }
Esempio n. 22
0
        public void SvgFillsAreCorrect()
        {
            var path = Path.Combine(PathToImages, "issues-24.svg");

            var svg = new SKSvg();

            svg.Load(path);
            var bmp = CreateBitmap(svg, SKColors.White);

            Assert.Equal(SKColors.White, bmp.GetPixel(11, 20));
        }
Esempio n. 23
0
        public void SvgStylesAreAlsoUsed()
        {
            var path = Path.Combine(PathToImages, "issues-22.svg");

            var svg = new SKSvg();

            svg.Load(path);
            var bmp = CreateBitmap(svg, SKColors.White);

            Assert.Equal(SKColors.White, bmp.GetPixel(bmp.Width / 2, bmp.Height / 2));
        }
        protected virtual SKSvg GetSvg(string filePath)
        {
            SKSvg svg = new SKSvg();

            svg.Load(filePath);
            if (svg?.Picture == null)
            {
                throw new NullReferenceException(nameof(svg.Picture));
            }
            return(svg);
        }
Esempio n. 25
0
 bool CheckSvg(string Path)
 {
     if (HasSvgExtension(Path))
     {
         //Is Image
         var Name = GetFilename(Path);
         var Imag = new SKSvg();
         Imag.Load(GetStream(Path));
         mImageFunction(Name, Imag);
     }
     return(true);
 }
Esempio n. 26
0
        public static SKSvg?LoadSvg(this Stream?str)
        {
            if (str == null)
            {
                return(null);
            }

            var svg = new SKSvg();

            svg.Load(str);
            return(svg);
        }
Esempio n. 27
0
        private void CanvasViewOnPaintSurface(object sender, SKPaintSurfaceEventArgs args)
        {
            SKCanvas canvas = args.Surface.Canvas;

            canvas.Clear();
            using (Stream stream = GetType().Assembly.GetManifestResourceStream("debugSVG.demo.svg"))
            {
                SKSvg svg = new SKSvg();
                svg.Load(stream);
                canvas.DrawPicture(svg.Picture);
            }
        }
Esempio n. 28
0
        public Task <SKSvg> LoadImageAsync(ImageSource imageSource, CancellationToken cancellationToken = new CancellationToken())
        {
            SKSvg           loader = new SKSvg();
            FileImageSource source = imageSource as FileImageSource;

            return(Task.Run(() =>
            {
                loader.Load(source.File);

                return loader;
            },
                            cancellationToken));
        }
Esempio n. 29
0
        public SkiaSharpSvgTools(SharedImageInfo info, ILogger logger)
            : base(info, logger)
        {
            var sw = new Stopwatch();

            sw.Start();

            svg = new SKSvg();
            svg.Load(Info.Filename);

            sw.Stop();
            Logger?.Log($"Open SVG took {sw.ElapsedMilliseconds}ms");
        }
Esempio n. 30
0
        public SkiaSharpSvgTools(string filename, Size?baseSize, Color?tintColor, ILogger logger)
            : base(filename, baseSize, tintColor, logger)
        {
            var sw = new Stopwatch();

            sw.Start();

            svg = new SKSvg();
            svg.Load(filename);

            sw.Stop();
            Logger?.Log($"Open SVG took {sw.ElapsedMilliseconds}ms ({filename})");
        }
		public async Task<Tuple<Stream, LoadingResult, ImageInformation>> Resolve(string identifier, TaskParameter parameters, CancellationToken token)
		{
			ImageSource source = parameters.Source;

			if (parameters.LoadingPlaceholderPath == identifier)
				source = parameters.LoadingPlaceholderSource;
			else if (parameters.ErrorPlaceholderPath == identifier)
				source = parameters.ErrorPlaceholderSource;

			var resolvedData = await Configuration.DataResolverFactory
			                                .GetResolver(identifier, source, parameters, Configuration)
			                                .Resolve(identifier, parameters, token);

			if (resolvedData?.Item1 == null)
				throw new FileNotFoundException(identifier);

			var svg = new SKSvg()
			{
				ThrowOnUnsupportedElement = false,
			};
			SKPicture picture;

			using (var svgStream = resolvedData.Item1)
			{
				picture = svg.Load(resolvedData?.Item1);
			}

			using (var bitmap = new SKBitmap(200, 200, true))
			using (var canvas = new SKCanvas(bitmap))
			{
				float canvasMin = Math.Min(200, 200);
				float svgMax = Math.Max(svg.Picture.Bounds.Width, svg.Picture.Bounds.Height);
				float scale = canvasMin / svgMax;
				var matrix = SKMatrix.MakeScale(scale, scale);
				canvas.DrawPicture(picture, ref matrix);

				using (var image = SKImage.FromBitmap(bitmap))
				{
					var stream = image.Encode()?.AsStream();
					return new Tuple<Stream, LoadingResult, ImageInformation>(stream, resolvedData.Item2, resolvedData.Item3);
				}
			}
		}