コード例 #1
0
ファイル: CalloutStyleRenderer.cs プロジェクト: Mapsui/Mapsui
        private static void DrawContent(CalloutStyle callout, SKCanvas canvas)
        {
            // Draw content
            if (callout.Content >= 0)
            {
                var strokeWidth = callout.StrokeWidth < 1 ? 1 : callout.StrokeWidth;
                var offsetX     = callout.ShadowWidth + strokeWidth * 2 + (callout.Padding.Left < callout.RectRadius * 0.5 ? callout.RectRadius * 0.5f : (float)callout.Padding.Left);
                var offsetY     = callout.ShadowWidth + strokeWidth * 2 + (callout.Padding.Top < callout.RectRadius * 0.5 ? callout.RectRadius * 0.5f : (float)callout.Padding.Top);

                switch (callout.ArrowAlignment)
                {
                case ArrowAlignment.Left:
                    offsetX += callout.ArrowHeight;
                    break;

                case ArrowAlignment.Top:
                    offsetY += callout.ArrowHeight;
                    break;
                }

                var offset = new SKPoint(offsetX, offsetY);

                if (callout.Type == CalloutType.Custom)
                {
                    // Get size of content
                    var bitmapInfo = BitmapHelper.LoadBitmap(BitmapRegistry.Instance.Get(callout.Content));

                    switch (bitmapInfo?.Type)
                    {
                    case BitmapType.Bitmap:
                        canvas.DrawImage(bitmapInfo.Bitmap, offset);
                        break;

                    case BitmapType.Sprite:
                        throw new Exception();

                    case BitmapType.Svg:
                        if (bitmapInfo.Svg != null)
                        {
                            using var skPaint = new SKPaint()
                                  {
                                      IsAntialias = true
                                  };
                            canvas.DrawPicture(bitmapInfo.Svg.Picture, offset, skPaint);
                        }

                        break;
                    }
                }
                else if (callout.Type == CalloutType.Single || callout.Type == CalloutType.Detail)
                {
                    var picture = (SKPicture)BitmapRegistry.Instance.Get(callout.Content);
                    using var skPaint = new SKPaint()
                          {
                              IsAntialias = true
                          };
                    canvas.DrawPicture(picture, offset, skPaint);
                }
            }
        }
コード例 #2
0
 public void DrawPicture(SKPicture picture, ref SKMatrix matrix, SKPaint paint = null)
 {
     canvas.DrawPicture(picture, ref matrix, paint);
     if (calculateBounds)
     {
         displayObject.addBoundingRect(matrix.TransX, matrix.TransY, picture.CullRect.Width, picture.CullRect.Height);
     }
 }
コード例 #3
0
        void canvasFront_PaintSurface(System.Object sender, SkiaSharp.Views.Forms.SKPaintSurfaceEventArgs e)
        {
            SKCanvas canvas = e.Surface.Canvas;

            canvas.Clear();

            SKMatrix matrix = DrawHelper.GetFullSvgScaledMatrix(e.Info.Width, e.Info.Height, pictureFront);

            canvas.DrawPicture(pictureFront, ref matrix);
            float offsetY = e.Info.Height / 5;

            foreach (DrawItem item in DrawData.DrawnPathsFront)
            {
                SKPath p           = new SKPath(item.Path);
                float  offsetCalcY = (float)DrawHelper.GetOffsetCalculationsForFullDisplay(item.Area, offsetY);
                float  offsetCalcX = ((e.Info.Width - matrix.TransX) / 2.0f) * 0.375f;

                p.Transform(SKMatrix.CreateScaleTranslation(0.25f, 0.25f, offsetCalcX, offsetCalcY));

                _data.Add(new SvgData
                {
                    BodyRegion  = item.Area.ToString(),
                    IsFront     = true,
                    StrokeColor = item.Paint.Color.ToFormsColor(),
                    StrokeWidth = item.Paint.StrokeWidth,
                    SvgPath     = p.ToSvgPathData(),
                    ConcernName = item.Name
                });

                canvas.DrawPath(p, DrawHelper.GetScaledPaintObject(item.Paint.Color, item.Paint.StrokeWidth));
            }

            imageDataF = e.Surface.Snapshot();
        }
コード例 #4
0
    private void SaveVector(Shape shape)
    {
        var svg = new SkiaSharp.Extended.Svg.SKSvg();

        svg.Load(shape.OutputPath);

        var svgRect = svg.Picture.CullRect;

        var(w, h) = CalculateResized((int)svgRect.Width, (int)svgRect.Height);
        float svgMax = Math.Max(w, h);

        float scale   = w / svgRect.Width;
        var   matrixS = SKMatrix.MakeScale(scale, scale);
        var   matrixT = SKMatrix.MakeTranslation((MAX_SIZE - w) / 2, (MAX_SIZE - h) / 2);
        var   matrix  = SKMatrix.MakeIdentity();

        SKMatrix.Concat(ref matrix, matrixT, matrixS);

        var target = new SKBitmap(MAX_SIZE, MAX_SIZE,
                                  SKImageInfo.PlatformColorType, SKAlphaType.Premul);

        using (target)
            using (var canvas = new SKCanvas(target))
            {
                canvas.Clear();
                canvas.DrawPicture(svg.Picture, ref matrix, _skPaint);
                SaveToFile(shape.Id, "svg", target);
            }
    }
コード例 #5
0
ファイル: SvgRenderer.cs プロジェクト: zoomvr/Mapsui
        public static void Draw(SKCanvas canvas, SkiaSharp.Extended.Svg.SKSvg svg, float x, float y, float orientation = 0,
                                float offsetX = 0, float offsetY = 0,
                                LabelStyle.HorizontalAlignmentEnum horizontalAlignment = LabelStyle.HorizontalAlignmentEnum.Left,
                                LabelStyle.VerticalAlignmentEnum verticalAlignment     = LabelStyle.VerticalAlignmentEnum.Top,
                                float opacity = 1f,
                                float scale   = 1f)
        {
            // todo: I assume we also need to apply opacity.
            // todo: It seems horizontalAlignment and verticalAlignment would make sense too. Is this similar to Anchor?

            canvas.Save();

            canvas.Translate(x, y);
            canvas.RotateDegrees(orientation, 0, 0); // todo: degrees or radians?
            canvas.Scale(scale, scale);

            var halfWidth  = svg.CanvasSize.Width / 2;
            var halfHeight = svg.CanvasSize.Height / 2;

            // 0/0 are assumed at center of image, but Svg has 0/0 at left top position
            canvas.Translate(-halfWidth + offsetX, -halfHeight - offsetY);

            canvas.DrawPicture(svg.Picture, new SKPaint()
            {
                IsAntialias = true
            });

            canvas.Restore();
        }
コード例 #6
0
        public static void Draw(SKCanvas canvas, SKSvg svg, float x, float y, float orientation = 0,
                                float offsetX = 0, float offsetY = 0, float opacity = 1f, float scale = 1f)
        {
            if (svg.Picture == null)
            {
                return;
            }

            canvas.Save();

            canvas.Translate(x, y);
            canvas.RotateDegrees(orientation, 0, 0); // todo: degrees or radians?
            canvas.Scale(scale, scale);

            var halfWidth  = svg.Picture.CullRect.Width / 2;
            var halfHeight = svg.Picture.CullRect.Height / 2;

            // 0/0 are assumed at center of image, but Svg has 0/0 at left top position
            canvas.Translate(-halfWidth + offsetX, -halfHeight - offsetY);

            var alpha        = Convert.ToByte(255 * opacity);
            var transparency = SKColors.White.WithAlpha(alpha);

            using (var cf = SKColorFilter.CreateBlendMode(transparency, SKBlendMode.DstIn))
            {
                using var skPaint = new SKPaint
                      {
                          IsAntialias = true,
                          ColorFilter = cf,
                      };
                canvas.DrawPicture(svg.Picture, skPaint);
            }

            canvas.Restore();
        }
コード例 #7
0
        void OnCanvasViewPaintSurface(object sender, SKPaintSurfaceEventArgs args)
        {
            SKCanvas canvas = args.Surface.Canvas;

            canvas.Clear();

            SKPaint  tempPaint = DrawHelper.GetCurrentPaintObject(true, brushColourToBeUsed, brushThickness);
            SKMatrix matrix    = DrawHelper.GetAreaSvgScaledMatrix(args.Info.Width, args.Info.Height, picture, areaUsed);

            canvas.DrawPicture(picture, ref matrix);

            foreach (DrawItem item in isFrontBody ? DrawData.DrawnPathsFront : DrawData.DrawnPathsBack)
            {
                if (areaUsed == item.Area)
                {
                    canvas.DrawPath(item.Path, item.Paint);
                }
            }

            foreach (DrawItem drawItem in completedPaths)
            {
                canvas.DrawPath(drawItem.Path, drawItem.Paint);
            }

            foreach (SKPath path in inProgressPaths.Values)
            {
                canvas.DrawPath(path, tempPaint);
            }

            btnSave.IsVisible   = completedPaths.Count > 0;
            btnUndo.IsVisible   = completedPaths.Count > 0;
            btnMirror.IsVisible = completedPaths.Count > 0;

            imageData = args.Surface.Snapshot();
        }
コード例 #8
0
        public ImageSource ProvideValue(IServiceProvider serviceProvider)
        {
            if (string.IsNullOrEmpty(ResourceName))
            {
                return(null);
            }

            if (!imagedataDictionary.TryGetValue(ResourceName, out var imagedata))
            {
                var assembly     = GetType().GetTypeInfo().Assembly;
                var assemblyName = assembly.GetName().Name;

                var skSvg = new SkiaSharp.Extended.Svg.SKSvg(new SKSize(Width, Height));

                skSvg.Load(assembly.GetManifestResourceStream(assemblyName + "." + ResourceName));

                var bitmap = new SKBitmap(Width, Height);
                var canvas = new SKCanvas(bitmap);
                canvas.Clear(SKColors.Transparent);
                canvas.DrawPicture(skSvg.Picture);
                canvas.Flush();
                canvas.Save();

                imagedata = SKImage.FromBitmap(bitmap).ToRasterImage().Encode(SKEncodedImageFormat.Png, 100);
                imagedataDictionary.Add(ResourceName, imagedata);
            }
            return(ImageSource.FromStream(() => imagedata.AsStream()));
        }
コード例 #9
0
        /// <summary>
        /// Creates the image.
        /// </summary>
        /// <returns>The image.</returns>
        /// <param name="stream">Stream.</param>
        /// <param name="width">Width.</param>
        /// <param name="height">Height.</param>
        /// <param name="color">Color.</param>
        public static Task <Stream> CreateImage(Stream stream, double width, double height, Color color)
        {
            var screenScale = SvgImageSource.ScreenScale;

            var svg = new SkiaSharp.Extended.Svg.SKSvg();

            svg.Load(stream);

            var size   = CalcSize(svg.Picture.CullRect.Size, width, height);
            var scale  = CalcScale(svg.Picture.CullRect.Size, size, screenScale);
            var matrix = SKMatrix.MakeScale(scale.Item1, scale.Item2);

            using (var bitmap = new SKBitmap((int)(size.Width * screenScale), (int)(size.Height * screenScale)))
                using (var canvas = new SKCanvas(bitmap))
                    using (var paint = new SKPaint())
                    {
                        if (!color.IsDefault)
                        {
                            paint.ColorFilter = SKColorFilter.CreateBlendMode(ToSKColor(color), SKBlendMode.SrcIn);
                        }

                        canvas.Clear(SKColors.Transparent); // very very important!
                        canvas.DrawPicture(svg.Picture, ref matrix, paint);

                        using (var image = SKImage.FromBitmap(bitmap))
                            using (var encoded = image.Encode())
                            {
                                var imageStream = new MemoryStream();
                                encoded.SaveTo(imageStream);
                                imageStream.Position = 0;
                                return(Task.FromResult(imageStream as Stream));
                            }
                    }
        }
コード例 #10
0
        public override void DrawUnscaled(SKCanvas canvas, float scale)
        {
            if (scale >= 1)
            {
                // draw using default scaling
                canvas.DrawPicture(svg.Picture, Paint);
            }
            else
            {
                // draw using raster downscaling
                var size = GetOriginalSize();

                // vector scaling has rounding issues, so first draw as intended
                var info = new SKImageInfo((int)size.Width, (int)size.Height);
                using var bmp = new SKBitmap(info);
                using var cvn = new SKCanvas(bmp);

                // draw to a larger canvas first
                cvn.Clear(SKColors.Transparent);
                cvn.DrawPicture(svg.Picture, Paint);

                // set the paint to be the highest quality it can find
                var paint = new SKPaint
                {
                    IsAntialias   = true,
                    FilterQuality = SKFilterQuality.High
                };

                // draw to the main canvas using the correct quality settings
                canvas.DrawBitmap(bmp, 0, 0, paint);
            }
        }
コード例 #11
0
        private void SKElement_OnPaintSurface(object sender, SKPaintSurfaceEventArgs e)
        {
            SKCanvas canvas = e.Surface.Canvas;

            canvas.Clear();

            if (Svg == null)
            {
                return;
            }

            SKImageInfo info = e.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);

            using (var paint = new SKPaint())
            {
                paint.ColorFilter = SKColorFilter.CreateBlendMode(Colors.Red.ToSKColor(), SKBlendMode.SrcIn);
                canvas.DrawPicture(Svg.Picture, paint);
            }
        }
コード例 #12
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);
            }
        }
コード例 #13
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));
                }
            }
        }
コード例 #14
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));
        }
コード例 #15
0
        public static void RenderSvg(SKCanvas canvas, SkiaSharp.Extended.Svg.SKSvg svg, float x, float y, float orientation = 0,
                                     float offsetX = 0, float offsetY = 0,
                                     LabelStyle.HorizontalAlignmentEnum horizontalAlignment = LabelStyle.HorizontalAlignmentEnum.Left,
                                     LabelStyle.VerticalAlignmentEnum verticalAlignment     = LabelStyle.VerticalAlignmentEnum.Top,
                                     float opacity = 1f,
                                     float scale   = 1f)
        {
            canvas.Save();

            canvas.Translate(x, y);
            canvas.RotateDegrees(orientation, 0, 0); // todo: degrees or radians?
            canvas.Scale(scale, scale);

            var halfWidth  = svg.CanvasSize.Width / 2;
            var halfHeight = svg.CanvasSize.Height / 2;

            // 0/0 are assumed at center of image, but Svg has 0/0 at left top position
            canvas.Translate(-halfWidth + offsetX, -halfHeight - offsetY);

            var rect = new SKRect(-halfWidth, -halfHeight, +halfWidth, +halfHeight);

            //var color = new SKColor(255, 255, 255, (byte)(255 * opacity));
            //var paint = new SKPaint { Color = color, FilterQuality = SKFilterQuality.High };

            canvas.DrawPicture(svg.Picture, null);

            canvas.Restore();
        }
コード例 #16
0
        private void Canvas_PaintSurface(object sender, SKPaintSurfaceEventArgs e)
        {
            SKImageInfo info    = e.Info;
            SKSurface   surface = e.Surface;
            SKCanvas    canvas  = surface.Canvas;
            var         paint   = new SKPaint
            {
                Style       = SKPaintStyle.Stroke,
                Color       = Color.Violet.ToSKColor(),
                StrokeWidth = 25,
            };

            if (ShowBase)
            {
                canvas.DrawPath(this.basePath, paint);
            }

            paths.ForEach(p => canvas.DrawPath(p, paint));
            if (null != path)
            {
                canvas.DrawPath(path, paint);
            }
            canvas.DrawPicture(sKSvg.Value.Picture);
            //canvas.DrawCircle(info.Width / 2, info.Height / 2, 100, paint);
        }
コード例 #17
0
ファイル: MainWindow.xaml.cs プロジェクト: tyty999/Svg.Skia
        private void OnPaintSurfaceSvg(SKCanvas canvas, int width, int height)
        {
            if (items.SelectedItem is Item item)
            {
                var stopwatch = Stopwatch.StartNew();

                canvas.Clear(SKColors.White);

                if (item.Picture != null)
                {
                    float pwidth  = item.Picture.CullRect.Width;
                    float pheight = item.Picture.CullRect.Height;
                    if (pwidth > 0f && pheight > 0f)
                    {
                        skElementSvg.Width  = pwidth;
                        skElementSvg.Height = pheight;
                        canvas.DrawPicture(item.Picture);
                    }
                }

                stopwatch.Stop();
                TextDrawTime.Text = $"{Math.Round(stopwatch.Elapsed.TotalMilliseconds, 3)}ms";
                Debug.WriteLine($"Draw: {Math.Round(stopwatch.Elapsed.TotalMilliseconds, 3)}ms");
            }
            else
            {
                canvas.Clear(SKColors.White);
            }
        }
コード例 #18
0
        public void Render(SKCanvas canvas)
        {
            if (AbsoluteVisible)
            {
                var textureBox    = Texture.ViewBox;
                var textureWidth  = textureBox.Width;
                var textureHeight = textureBox.Height;

                var scaleX = this.Width / textureWidth;
                var scaleY = this.Height / textureHeight;

                SKMatrix scaleMatrix = SKMatrix.MakeScale(scaleX, scaleY);
                // Gum uses counter clockwise rotation, Skia uses clockwise, so invert:
                SKMatrix rotationMatrix  = SKMatrix.MakeRotationDegrees(-Rotation);
                SKMatrix translateMatrix = SKMatrix.MakeTranslation(this.GetAbsoluteX(), this.GetAbsoluteY());
                SKMatrix result          = SKMatrix.MakeIdentity();

                SKMatrix.Concat(
                    ref result, rotationMatrix, scaleMatrix);
                SKMatrix.Concat(
                    ref result, translateMatrix, result);

                canvas.DrawPicture(Texture.Picture, ref result);
            }
        }
コード例 #19
0
        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));
                }
            }
        }
コード例 #20
0
 private void DrawPicture(SKCanvas canvas, SKPicture picture, double dx, double dy, double zx, double zy)
 {
     canvas.Save();
     canvas.Translate((float)dx, (float)dy);
     canvas.Scale((float)zx, (float)zy);
     canvas.DrawPicture(picture);
     canvas.Restore();
 }
コード例 #21
0
 public static void Draw(this SKPicture skPicture, SKColor background, float scaleX, float scaleY, SKCanvas skCanvas)
 {
     skCanvas.DrawColor(background);
     skCanvas.Save();
     skCanvas.Scale(scaleX, scaleY);
     skCanvas.DrawPicture(skPicture);
     skCanvas.Restore();
 }
コード例 #22
0
ファイル: Helpers.cs プロジェクト: 5ye/PetProjects
        /// <summary>
        /// Назначить из Assets\svg SVG-картинку на ImageView
        /// </summary>
        /// <param name="imgView"></param>
        /// <param name="fileName"></param>
        /// <param name="wantedWidth"></param>
        /// <param name="wantedHeight"></param>
        /// <param name="preprocess"></param>
        public static void AssignSvg([NotNull] ImageView imgView, string fileName, Action <XmlDocument> preprocess,
                                     int?wantedWidth = null, int?wantedHeight = null)
        {
            if (wantedWidth == null)
            {
                wantedWidth = imgView.Width;
            }
            if (wantedHeight == null)
            {
                wantedHeight = imgView.Height;
            }
            const int bestQuality  = 100;
            var       parentColor  = TryGetBackgroundColor(imgView);
            var       viewActivity = (Activity)imgView.Context;

            using (var reader = new StreamReader(viewActivity.Assets.Open(Path.Combine("svg", Path.ChangeExtension(fileName, "svg").AssertNull()))))
            {
                var xmlDoc = new XmlDocument();
                xmlDoc.Load(reader);
                xmlDoc.DocumentElement.VoidAssertNull();
                xmlDoc.DocumentElement.SetAttribute("width", wantedWidth.ToString());
                xmlDoc.DocumentElement.SetAttribute("height", wantedHeight.ToString());
                preprocess?.Invoke(xmlDoc);
                if (parentColor.HasValue)
                {
                    var bkColorRect = xmlDoc.CreateElement("rect");
                    bkColorRect.SetAttribute("style", $"fill: {parentColor.Value.ToHtmlValue()}");
                    bkColorRect.SetAttribute("x", "0");
                    bkColorRect.SetAttribute("y", "0");
                    bkColorRect.SetAttribute("width", wantedWidth.ToString());
                    bkColorRect.SetAttribute("height", wantedHeight.ToString());
                    xmlDoc.DocumentElement.AssertNull().InsertAfter(bkColorRect, null);
                }
                using (var alterStream = new MemoryStream())
                {
                    xmlDoc.Save(alterStream);
                    alterStream.Seek(0, SeekOrigin.Begin);
                    var svg = new SkiaSharp.Extended.Svg.SKSvg(new SKSize(wantedWidth.Value, wantedHeight.Value));
                    svg.Load(alterStream);
                    using (var svgBitmap = new SKBitmap((int)svg.CanvasSize.Width, (int)svg.CanvasSize.Height))
                    {
                        using (var canvas = new SKCanvas(svgBitmap))
                        {
                            canvas.DrawPicture(svg.Picture);
                            canvas.Flush();
                            canvas.Save();
                        }
                        using (var image = SKImage.FromBitmap(svgBitmap))
                            using (var data = image.Encode(SKEncodedImageFormat.Png, bestQuality))
                            {
                                var bmpArray = data.ToArray();
                                imgView.SetImageBitmap(BitmapFactory.DecodeByteArray(bmpArray, 0, bmpArray.Length));
                            }
                    }
                }
            }
        }
コード例 #23
0
 public void Render(SKCanvas canvas, float angleInRadians, SKPoint center, float scale)
 {
     if (_svgScene == null)
     {
         _svgScene = LoadScene();
     }
     canvas.Clear(SKColors.White);
     canvas.DrawPicture(_svgScene);
 }
コード例 #24
0
        public static ImageSource GetAsImageSource(string svgImage, float width, float height, Color color)
        {
            var scaleFactor = PlatformHelper.GetScaleFactor();

            SkiaSharp.Extended.Svg.SKSvg svg = PlatformHelper.Load(svgImage);

            var svgSize = svg.Picture.CullRect;
            var svgMax  = Math.Max(svgSize.Width, svgSize.Height);

            var canvasMin = Math.Min((int)(width * scaleFactor), (int)(height * scaleFactor));
            var scale     = canvasMin / svgMax;
            var matrix    = SKMatrix.MakeScale(scale, scale);

            var bitmap = new SKBitmap((int)(width * scaleFactor), (int)(height * scaleFactor));

            var canvas = new SKCanvas(bitmap);

            canvas.Clear();

            if (color != Color.Default)
            {
                var paint = new SKPaint()
                {
                    ColorFilter = SKColorFilter.CreateBlendMode(color.ToSKColor(), SKBlendMode.SrcIn)
                };

                canvas.DrawPicture(svg.Picture, ref matrix, paint);
            }
            else
            {
                canvas.DrawPicture(svg.Picture, ref matrix);
            }

            var image = SKImage.FromBitmap(bitmap);

            var encoded = image.Encode();

            var stream = encoded.AsStream();
            var bytes  = ReadFully(stream);

            var source = ImageSource.FromStream(() => new MemoryStream(bytes));

            return(source);
        }
コード例 #25
0
        private void SkCanvas_OnPaintSurface(object sender, SKPaintGLSurfaceEventArgs e)
        {
            SKImageInfo info = new SKImageInfo(e.BackendRenderTarget.Width, e.BackendRenderTarget.Height, e.ColorType);

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

            surfaceCanvas.Clear();

            surfaceCanvas.SetMatrix(_canvasMatrix);


            if (_picture == null)
            {
                using (SKPictureRecorder pictureRecorder = new SKPictureRecorder())
                    using (SKCanvas canvas = pictureRecorder.BeginRecording(info.Rect))
                        using (SKPath path = new SKPath())
                        {
                            /*
                             * Draw path with multiple segments(>=3).
                             * Then every time you translate the surfaceCanvas, it consumes more GPU memory.
                             */
                            path.CubicTo(150, 50, 200, 125, 300, 25);

                            // path.LineTo(80, 125);
                            // path.LineTo(130, 75);
                            // path.LineTo(200, 205);


                            canvas.DrawPath(path, _paint);

                            // Fine with DrawRoundRect or DrawText
                            // canvas.DrawText("TEXT", new SKPoint(50, 50), _paint);
                            // canvas.DrawRoundRect(120,120,300,220,12,12,paint);

                            _picture = pictureRecorder.EndRecording();
                        }
            }


            surfaceCanvas.DrawPicture(_picture);

            /*
             * Directly drawing on surfaceCanvas is fine.
             */
            // using (SKPath path = new SKPath())
            // {
            //     path.CubicTo(150, 50, 200, 125, 300, 25);
            //
            //     path.LineTo(80, 125);
            //     path.LineTo(130, 75);
            //     path.LineTo(200, 205);
            //
            //     surfaceCanvas.DrawPath(path, _paint);
            // }
        }
コード例 #26
0
        public static void Draw(SKCanvas canvas, IReadOnlyViewport viewport,
                                float opacity, Point destination, CalloutStyle calloutStyle)
        {
            if (calloutStyle.BitmapId < 0 || calloutStyle.Invalidated)
            {
                if (calloutStyle.Content < 0 && calloutStyle.Type == CalloutType.Custom)
                {
                    return;
                }

                if (calloutStyle.Invalidated)
                {
                    UpdateContent(calloutStyle);
                }

                RenderCallout(calloutStyle);
            }

            // Now we have the complete callout rendered, so we could draw it
            if (calloutStyle.BitmapId < 0)
            {
                return;
            }

            var picture = (SKPicture)BitmapRegistry.Instance.Get(calloutStyle.BitmapId);

            // Calc offset (relative or absolute)
            var symbolOffsetX = calloutStyle.SymbolOffset.IsRelative ? picture.CullRect.Width * (float)calloutStyle.SymbolOffset.X : (float)calloutStyle.SymbolOffset.X;
            var symbolOffsetY = calloutStyle.SymbolOffset.IsRelative ? picture.CullRect.Height * (float)calloutStyle.SymbolOffset.Y : (float)calloutStyle.SymbolOffset.Y;

            var rotation = (float)calloutStyle.SymbolRotation;

            if (calloutStyle.RotateWithMap)
            {
                rotation += (float)viewport.Rotation;
            }

            // Save state of the canvas, so we could move and rotate the canvas
            canvas.Save();

            // Move 0/0 to the Anchor point of Callout
            canvas.Translate((float)destination.X - symbolOffsetX, (float)destination.Y - symbolOffsetY);
            canvas.Scale((float)calloutStyle.SymbolScale, (float)calloutStyle.SymbolScale);

            // 0/0 are assumed at center of image, but Picture has 0/0 at left top position
            canvas.RotateDegrees(rotation);
            canvas.Translate((float)calloutStyle.Offset.X, (float)calloutStyle.Offset.Y);

            canvas.DrawPicture(picture, new SKPaint()
            {
                IsAntialias = true
            });

            canvas.Restore();
        }
コード例 #27
0
        public bool Draw(SKCanvas canvas, IReadOnlyViewport viewport, ILayer layer, IFeature feature, IStyle style,
                         ISymbolCache symbolCache)
        {
            var image = ((SvgStyle)style).GetImage();

            if (image == null)
            {
                return(true);
            }
            var center = viewport.Center;

            //SvgRenderer.Draw(canvas, image, -(float)viewport.Center.X, (float)viewport.Center.Y, (float)viewport.Rotation, 0,0,default, default, default, (float)viewport.Resolution);

            canvas.Save();


            var zoom = 1 / (float)viewport.Resolution;

            var canvasSize = canvas.LocalClipBounds;

            var canvasCenterX = canvasSize.Width / 2;
            var canvasCenterY = canvasSize.Height / 2;


            //float width = (float)MapPage.currentBounds.Width;
            //float height = (float)MapPage.currentBounds.Height;


            float width  = image.Picture.CullRect.Width;
            float height = image.Picture.CullRect.Height;

            float num1 = (width / 2) * zoom;
            float num2 = (-height) * zoom;

            canvas.Translate(canvasCenterX, num2 + canvasCenterY);

            canvas.Translate(-(float)viewport.Center.X * zoom, (float)viewport.Center.Y * zoom);

            canvas.Scale(zoom, zoom);


            canvas.RotateDegrees((float)viewport.Rotation, 0.0f, 0.0f);


            canvas.DrawPicture(image.Picture, new SKPaint()
            {
                IsAntialias = true
            });
            canvas.Restore();



            return(true);
        }
コード例 #28
0
ファイル: Engine.cs プロジェクト: jgiacomini/xamarin.flutter
        public void Render(LayerTree layer_tree)
        {
            if (layer_tree == null)
            {
                return;
            }

            SKSizeI frame_size = new SKSizeI((int)_physicalWidth,
                                             (int)_physicalHeight);

            if (frame_size.IsEmpty)
            {
                return;
            }

            layer_tree.set_frame_size(frame_size);

            // ** Start Hack
            // I just wanted it outputted at this time, rather than frame dependant

            // var picture = layer_tree.Flatten(new SKRect(0, 0, frame_size.Width, frame_size.Height));
            var picture = ((PictureLayer)((ContainerLayer)layer_tree.root_layer_).layers_[0]).picture();

            //// get the screen density for scaling

            //var scale = _scale;
            //var scaledSize = new SKSize(frame_size.Width / scale, frame_size.Height / scale);

            ////// handle the device screen density
            //_canvas.Scale(_scale);

            //// make sure the canvas is blank
            //_canvas.Clear(SKColors.White);

            //// draw some text
            //var paint = new SKPaint
            //{
            //    Color = SKColors.Black,
            //    IsAntialias = true,
            //    Style = SKPaintStyle.Fill,
            //    TextAlign = SKTextAlign.Center,
            //    TextSize = 24
            //};
            //var coord = new SKPoint(scaledSize.Width / 2, (scaledSize.Height + paint.TextSize) / 2);
            //_canvas.DrawText("Xamarin.Flutter", coord, paint);
            _canvas.DrawPicture(picture);

            //_canvas.DrawText("Hello", scaledSize.Width / 2, (scaledSize.Height + paint.TextSize) / 2, paint);

            // ** End Hack

            // This is where we are meant to go
            //animator_.Render(layer_tree);
        }
コード例 #29
0
        protected override void OnDrawSample(SKCanvas canvas, int width, int height)
        {
            canvas.Clear(SKColors.White);

            float canvasMin = Math.Min(width, height);
            float svgMax    = Math.Max(svg.Picture.CullRect.Width, svg.Picture.CullRect.Height);
            float scale     = canvasMin / svgMax;
            var   matrix    = SKMatrix.MakeScale(scale, scale);

            canvas.DrawPicture(svg.Picture, ref matrix);
        }
コード例 #30
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);
            }
        }