Exemple #1
1
        public static void RenderRaster(SKCanvas canvas, SKBitmap bitmap, SKRect rect, float opacity = 1f)
        {
            // Better for quality. Helps to compare to WPF
            var color = new SKColor(255, 255, 255, (byte)(255 * opacity));
            var paint = new SKPaint { Color = color, FilterQuality = SKFilterQuality.High };
            canvas.DrawBitmap(bitmap, rect, paint);

            // Better for performance:
            canvas.DrawBitmap(bitmap, rect);
        }
        public MySkiaCanvas(
            int horizontalPageNum,
            int verticalPageNum,
            int left, int top,
            int width,
            int height)
        {


#if DEBUG
            debug_canvas_id = dbug_canvasCount + 1;
            dbug_canvasCount += 1;
#endif


            this.pageNumFlags = (horizontalPageNum << 8) | verticalPageNum;
            //2. dimension
            this.left = left;
            this.top = top;
            this.right = left + width;
            this.bottom = top + height;

            currentClipRect = new SKRect(0, 0, width, height);
            CreateGraphicsFromNativeHdc(width, height);

            this.StrokeWidth = 1;
        }
Exemple #3
0
        public static void RenderTexture(SKCanvas canvas, SKBitmap bitmap, float x, float y, float orientation = 0,
            float offsetX = 0, float offsetY = 0,
            LabelStyle.HorizontalAlignmentEnum horizontalAlignment = LabelStyle.HorizontalAlignmentEnum.Center,
            LabelStyle.VerticalAlignmentEnum verticalAlignment = LabelStyle.VerticalAlignmentEnum.Center,
            float opacity = 1f,
            float scale = 1f)
        {
            canvas.Save();

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

            x = offsetX + DetermineHorizontalAlignmentCorrection(horizontalAlignment, bitmap.Width);
            y = -offsetY + DetermineVerticalAlignmentCorrection(verticalAlignment, bitmap.Height);

            var halfWidth = bitmap.Width/2;
            var halfHeight = bitmap.Height/2;

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

            RenderTexture(canvas, bitmap, rect, opacity);

            canvas.Restore();
        }
Exemple #4
0
        //-----------------------------------------------------------------------------
        // Call this whenever either the Source or the Label changes
        private void SetElementWidth()
        {
            if (Label == null || bmpSrc == null)
            {
                return;
            }

            var scaleFactor = getScreenScaleFactor();

            Log.L("SEW: scaleFactor " + scaleFactor);

            // determine space needed for text -- units are actual device pixels
            using (SKPaint textPaint = new SKPaint())
            {
                Log.L("SEW: textSize " + textPaint.TextSize);
                textPaint.TextSize = (textPaint.TextSize + textSizeAdjustment); // * scaleFactor;
                var textBounds = new SkiaSharp.SKRect();

                textPaint.MeasureText("X", ref textBounds);
                textCoreHeight = textBounds.Height;
                Log.L("SEW: core height " + textCoreHeight);

                textPaint.MeasureText(Label, ref textBounds);
                desiredElementWidth = (textBounds.Width + padding * 2); // * scaleFactor;
                Log.L("SEW: source width " + textBounds.Width);
                Log.L("SEW: desired width " + desiredElementWidth);
            }

            // make sure width is >= source bitmap width
            Log.L("SEW: bmp wh " + bmpSrc.Width + ", " + bmpSrc.Height);
            var h = this.ActualHeight; // in XAML units (docs say pixels)

            Log.L("SEW: actual h " + h);
            var scale = (float)h / (float)bmpSrc.Height;

            Log.L("SEW: scale " + scale);
            var scaledBmpWidth = scale * bmpSrc.Width;

            Log.L("SEW: sw " + scaledBmpWidth);

            if (scaledBmpWidth > desiredElementWidth)
            {
                desiredElementWidth = scaledBmpWidth;
            }
            Log.L("SEW: w " + desiredElementWidth);

            // set element width
            Width = desiredElementWidth;
        }
Exemple #5
0
        /// <summary>
        /// Converts the offline-standalone PlaceInfo entries into SKRects for drawing on a SlippyMap. Used to visualize the offline mode beahvior of areas.
        /// </summary>
        /// <param name="pi">PlaceInfo object to convert</param>
        /// <param name="info">ImageStats for the resulting map tile</param>
        /// <returns>The SKRect representing the standaloneDb size of the PlaceInfo</returns>
        public SkiaSharp.SKRect PlaceInfoToRect(PraxisCore.StandaloneDbTables.PlaceInfo2 pi, ImageStats info)
        {
            SkiaSharp.SKRect r         = new SkiaSharp.SKRect();
            float            heightMod = (float)pi.height / 2;
            float            widthMod  = (float)pi.width / 2;

            r.Left   = (float)pi.lonCenter - widthMod;
            r.Left   = (float)(r.Left - info.area.WestLongitude) * (float)(1 / info.degreesPerPixelX);
            r.Right  = (float)pi.lonCenter + widthMod;
            r.Right  = (float)(r.Right - info.area.WestLongitude) * (float)(1 / info.degreesPerPixelX);
            r.Top    = (float)pi.latCenter + heightMod;
            r.Top    = (float)(r.Top - info.area.SouthLatitude) * (float)(1 / info.degreesPerPixelY);
            r.Bottom = (float)pi.latCenter - heightMod;
            r.Bottom = (float)(r.Bottom - info.area.SouthLatitude) * (float)(1 / info.degreesPerPixelY);

            return(r);
        }
Exemple #6
0
        private static SKBitmap CreateLabelAsBitmap(LabelStyle style, string text, SKPaint paint)
        {
            var rect = new SKRect();
            paint.MeasureText(text, ref rect);

            var backRect = new SKRect(0, 0, rect.Width + 6, rect.Height + 6);

            var bitmap = new SKBitmap((int)backRect.Width, (int)backRect.Height);

            using (var target = new SKCanvas(bitmap))
            {
                target.Clear();

                DrawBackground(style, backRect, target);
                target.DrawText(text, -rect.Left + 3, -rect.Top +3, paint);
                return bitmap;
            }
        }
Exemple #7
0
        private SKPoint GetTextOrigin(ShapeStyle style, ref SKRect rect, ref SKRect size)
        {
            double rwidth = Math.Abs(rect.Right - rect.Left);
            double rheight = Math.Abs(rect.Bottom - rect.Top);
            double swidth = Math.Abs(size.Right - size.Left);
            double sheight = Math.Abs(size.Bottom - size.Top);
            double ox, oy;

            switch (style.TextStyle.TextHAlignment)
            {
                case TextHAlignment.Left:
                    ox = rect.Left;
                    break;
                case TextHAlignment.Right:
                    ox = rect.Right - swidth;
                    break;
                case TextHAlignment.Center:
                default:
                    ox = (rect.Left + rwidth / 2f) - (swidth / 2f);
                    break;
            }

            switch (style.TextStyle.TextVAlignment)
            {
                case TextVAlignment.Top:
                    oy = rect.Top;
                    break;
                case TextVAlignment.Bottom:
                    oy = rect.Bottom - sheight;
                    break;
                case TextVAlignment.Center:
                default:
                    oy = (rect.Bottom - rheight / 2f) - (sheight / 2f);
                    break;
            }

            return new SKPoint((float)ox, (float)oy);
        }
Exemple #8
0
        private SKPicture Load(XDocument xdoc)
        {
            var svg = xdoc.Root;
            var ns  = svg.Name.Namespace;

            // find the defs (gradients) - and follow all hrefs
            foreach (var d in svg.Descendants())
            {
                var id = d.Attribute("id")?.Value?.Trim();
                if (!string.IsNullOrEmpty(id))
                {
                    defs[id] = ReadDefinition(d);
                }
            }

            Version     = svg.Attribute("version")?.Value;
            Title       = svg.Element(ns + "title")?.Value;
            Description = svg.Element(ns + "desc")?.Value ?? svg.Element(ns + "description")?.Value;

            // TODO: parse the "preserveAspectRatio" values properly
            var preserveAspectRatio = svg.Attribute("preserveAspectRatio")?.Value;

            // get the SVG dimensions
            var viewBoxA = svg.Attribute("viewBox") ?? svg.Attribute("viewPort");

            if (viewBoxA != null)
            {
                ViewBox = ReadRectangle(viewBoxA.Value);
            }

            if (CanvasSize.IsEmpty)
            {
                // get the user dimensions
                var widthA  = svg.Attribute("width");
                var heightA = svg.Attribute("height");
                var width   = ReadNumber(widthA);
                var height  = ReadNumber(heightA);
                var size    = new SKSize(width, height);

                if (widthA == null)
                {
                    size.Width = ViewBox.Width;
                }
                else if (widthA.Value.Contains("%"))
                {
                    size.Width *= ViewBox.Width;
                }
                if (heightA == null)
                {
                    size.Height = ViewBox.Height;
                }
                else if (heightA != null && heightA.Value.Contains("%"))
                {
                    size.Height *= ViewBox.Height;
                }

                // set the property
                CanvasSize = size;
            }

            // create the picture from the elements
            using (var recorder = new SKPictureRecorder())
                using (var canvas = recorder.BeginRecording(SKRect.Create(CanvasSize)))
                {
                    // if there is no viewbox, then we don't do anything, otherwise
                    // scale the SVG dimensions to fit inside the user dimensions
                    if (!ViewBox.IsEmpty && (ViewBox.Width != CanvasSize.Width || ViewBox.Height != CanvasSize.Height))
                    {
                        if (preserveAspectRatio == "none")
                        {
                            canvas.Scale(CanvasSize.Width / ViewBox.Width, CanvasSize.Height / ViewBox.Height);
                        }
                        else
                        {
                            // TODO: just center scale for now
                            var scale    = Math.Min(CanvasSize.Width / ViewBox.Width, CanvasSize.Height / ViewBox.Height);
                            var centered = SKRect.Create(CanvasSize).AspectFit(ViewBox.Size);
                            canvas.Translate(centered.Left, centered.Top);
                            canvas.Scale(scale, scale);
                        }
                    }

                    // translate the canvas by the viewBox origin
                    canvas.Translate(-ViewBox.Left, -ViewBox.Top);

                    // if the viewbox was specified, then crop to that
                    if (!ViewBox.IsEmpty)
                    {
                        canvas.ClipRect(ViewBox);
                    }

                    LoadElements(svg.Elements(), canvas);

                    Picture = recorder.EndRecording();
                }

            return(Picture);
        }
Exemple #9
0
 public bool GetLocalClipBounds(out SKRect bounds)
 {
     return(SkiaApi.sk_canvas_get_local_clip_bounds(Handle, out bounds));
 }
Exemple #10
0
 public void AddRoundedRect(SKRect rect, float rx, float ry, SKPathDirection dir = SKPathDirection.Clockwise)
 {
     AddRoundRect(rect, rx, ry, dir);
 }
Exemple #11
0
 public void DrawLinkDestinationAnnotation(SKRect rect, SKData value)
 {
     SkiaApi.sk_canvas_draw_link_destination_annotation(Handle, ref rect, value == null ? IntPtr.Zero : value.Handle);
 }
Exemple #12
0
 public void DrawUrlAnnotation(SKRect rect, SKData value)
 {
     SkiaApi.sk_canvas_draw_url_annotation(Handle, ref rect, value == null ? IntPtr.Zero : value.Handle);
 }
Exemple #13
0
 public bool QuickReject(SKRect rect)
 {
     return(SkiaApi.sk_canvas_quick_reject(Handle, ref rect));
 }
Exemple #14
0
 public void ClipRect(SKRect rect, SKClipOperation operation = SKClipOperation.Intersect, bool antialias = false)
 {
     SkiaApi.sk_canvas_clip_rect_with_operation(Handle, ref rect, operation, antialias);
 }
Exemple #15
0
        public void AddPositionedRun(SKPaint font, ushort[] glyphs, SKPoint[] positions, string text, uint[] clusters, SKRect bounds)
        {
            var utf8Text = StringUtilities.GetEncodedText(text, SKTextEncoding.Utf8);

            AddPositionedRun(font, glyphs, positions, utf8Text, clusters, (SKRect?)bounds);
        }
Exemple #16
0
 public void AddHorizontalRun(SKPaint font, float y, ushort[] glyphs, float[] positions, byte[] text, uint[] clusters, SKRect bounds) =>
 AddHorizontalRun(font, y, glyphs, positions, text, clusters, (SKRect?)bounds);
Exemple #17
0
 public void AddHorizontalRun(SKPaint font, float y, ushort[] glyphs, float[] positions, SKRect bounds) =>
 AddHorizontalRun(font, y, glyphs, positions, ReadOnlySpan <byte> .Empty, ReadOnlySpan <uint> .Empty, bounds);
Exemple #18
0
 public void AddRun(SKPaint font, float x, float y, ushort[] glyphs, byte[] text, uint[] clusters, SKRect bounds) =>
 AddRun(font, x, y, glyphs, text, clusters, (SKRect?)bounds);
Exemple #19
0
 public void AddRun(SKPaint font, float x, float y, ushort[] glyphs, SKRect bounds) =>
 AddRun(font, x, y, glyphs, ReadOnlySpan <byte> .Empty, ReadOnlySpan <uint> .Empty, bounds);
Exemple #20
0
        public void AddRun(SKPaint font, float x, float y, ushort[] glyphs, string text, uint[] clusters, SKRect bounds)
        {
            var utf8Text = StringUtilities.GetEncodedText(text, SKTextEncoding.Utf8);

            AddRun(font, x, y, glyphs, utf8Text, clusters, (SKRect?)bounds);
        }
Exemple #21
0
 public SKCanvas BeginPage(float width, float height, SKRect content)
 {
     return(GetObject <SKCanvas> (SkiaApi.sk_document_begin_page(Handle, width, height, ref content), false));
 }
Exemple #22
0
 public void ClipRect(SKRect rect, SKRegionOperation operation, bool antialias = false)
 {
     ClipRect(rect, (SKClipOperation)(int)operation, antialias);
 }
Exemple #23
0
 public void AddPositionedRun(SKPaint font, ushort[] glyphs, SKPoint[] positions, SKRect bounds) =>
 AddPositionedRun(font, glyphs, positions, ReadOnlySpan <byte> .Empty, ReadOnlySpan <uint> .Empty, bounds);
Exemple #24
0
 public bool GetClipBounds(ref SKRect bounds)
 {
     return(SkiaApi.sk_canvas_get_clip_bounds(Handle, ref bounds));
 }
Exemple #25
0
 public void AddPositionedRun(SKPaint font, ushort[] glyphs, SKPoint[] positions, byte[] text, uint[] clusters, SKRect bounds) =>
 AddPositionedRun(font, glyphs, positions, text, clusters, (SKRect?)bounds);
Exemple #26
0
 public void DrawAnnotation(SKRect rect, string key, SKData value)
 {
     SkiaApi.sk_canvas_draw_annotation(Handle, ref rect, StringUtilities.GetEncodedText(key, SKTextEncoding.Utf8), value == null ? IntPtr.Zero : value.Handle);
 }
			public CropRect(SKRect rect, SKCropRectFlags flags = SKCropRectFlags.HasAll)
				: this(SkiaApi.sk_imagefilter_croprect_new_with_rect(ref rect, flags), true)
			{
			}
Exemple #28
0
 public int SaveLayer(SKRect limit, SKPaint paint)
 {
     return(SkiaApi.sk_canvas_save_layer(Handle, ref limit, paint == null ? IntPtr.Zero : paint.Handle));
 }
Exemple #29
0
 public void DrawBitmap(SKBitmap bitmap, SKRect source, SKRect dest, SKPaint paint = null)
 {
     if (bitmap == null)
         throw new ArgumentNullException ("bitmap");
     SkiaApi.sk_canvas_draw_bitmap_rect (Handle, bitmap.Handle, ref source, ref dest, paint == null ? IntPtr.Zero : paint.Handle);
 }
Exemple #30
0
 public bool GetTightBounds(out SKRect result)
 {
     return(SkiaApi.sk_pathop_tight_bounds(Handle, out result));
 }
Exemple #31
0
        public void DrawBitmapNinePatch(SKBitmap bitmap, SKRectI center, SKRect dst, SKPaint paint = null)
        {
            if (bitmap == null)
                throw new ArgumentNullException (nameof (bitmap));
            // the "center" rect must fit inside the bitmap "rect"
            if (!SKRect.Create (bitmap.Info.Size).Contains (center))
                throw new ArgumentOutOfRangeException (nameof (center));

            var xDivs = new [] { center.Left, center.Right };
            var yDivs = new [] { center.Top, center.Bottom };
            DrawBitmapLattice (bitmap, xDivs, yDivs, dst, paint);
        }
 public SKCanvas BeginRecording(SKRect cullRect)
 {
     return(OwnedBy(SKCanvas.GetObject(SkiaApi.sk_picture_recorder_begin_recording(Handle, &cullRect), false), this));
 }
Exemple #33
0
 public bool GetClipBounds(ref SKRect bounds)
 {
     return(GetLocalClipBounds(out bounds));
 }
Exemple #34
0
        } // End Function LoadImage

        private void DrawImage()
        {
            int bitness = System.IntPtr.Size * 8;

            System.Console.WriteLine(bitness);


            // https://developer.xamarin.com/guides/cross-platform/drawing/introduction/
            // https://developer.xamarin.com/api/type/SkiaSharp.SKSurface/
            // https://forums.xamarin.com/discussion/77883/skiasharp-graphics-basics


            // Make sure the Microsoft Visual C++ 2015 Redistributable is installed if this error occurs:
            // Unable to load DLL 'libSkiaSharp.dll': The specified module could not be found.
            using (SKSurface surface = SKSurface.Create(width: 640, height: 480, colorType: SKColorType.Bgra8888, alphaType: SKAlphaType.Premul))
            {
                SKCanvas canvas = surface.Canvas;

                canvas.Clear(SKColors.Transparent);


                using (SKPaint paint = new SKPaint())
                {
                    // paint.ImageFilter = SKImageFilter.CreateBlur(5, 5); // Dispose !
                    paint.IsAntialias = true;
                    // paint.Color = new SKColor(0xff, 0x00, 0xff);
                    paint.Color = new SKColor(0x2c, 0x3e, 0x50);

                    paint.StrokeCap = SKStrokeCap.Round;

                    paint.Typeface = SkiaSharp.SKTypeface.FromFamilyName("Impact", SKTypefaceStyle.Bold);
                    paint.TextSize = 12;

                    canvas.DrawText("foobar", 10, 10, paint);
                    // SkiaSharp.SKRect rect = new SkiaSharp.SKRect();
                    SkiaSharp.SKRect rect = MeasureText("foobar", "Impact", 12, SKTypefaceStyle.Bold);
                    // paint.MeasureText("foobar", ref rect);
                    System.Console.WriteLine(rect);

                    SKRect textOverlayRectangle = new SKRect();
                    textOverlayRectangle.Left = 9;                // x
                    textOverlayRectangle.Top  = 10 - rect.Height; // y

                    textOverlayRectangle.Right  = textOverlayRectangle.Left + rect.Width;
                    textOverlayRectangle.Bottom = textOverlayRectangle.Top + rect.Height;

                    // canvas.DrawRect(textOverlayRectangle, paint);



                    // https://chromium.googlesource.com/external/skia/+/master/experimental/SkiaExamples/HelloSkiaExample.cpp
                    SkiaSharp.SKPoint[] linearPoints = new SkiaSharp.SKPoint[] {
                        new SkiaSharp.SKPoint(0, 0),
                        new SkiaSharp.SKPoint(300, 300)
                    };
                    SkiaSharp.SKColor[] linearColors = new SkiaSharp.SKColor[] { SkiaSharp.SKColors.Green, SkiaSharp.SKColors.Black };


                    // canvas.Restore();
                    // canvas.Translate(100, 200);
                    // canvas.RotateDegrees(45);

                    // SKShader shader = SkiaSharp.SKShader.CreateLinearGradient(linearPoints[0], linearPoints[1], linearColors, new float[] { 1.0f, 2000.0f }, SKShaderTileMode.Repeat);
                    // paint.Shader = shader;

                    SkiaSharp.SKBitmap shaderPattern = LoadImage(MapProjectPath(@"~mytile.png"));
                    SKShader           hatchShader   = SkiaSharp.SKShader.CreateBitmap(shaderPattern, SKShaderTileMode.Mirror, SKShaderTileMode.Repeat);
                    paint.Shader = hatchShader;



                    // create the Xamagon path
                    using (SKPath path = new SKPath())
                    {
                        path.MoveTo(71.4311121f, 56f);
                        path.CubicTo(68.6763107f, 56.0058575f, 65.9796704f, 57.5737917f, 64.5928855f, 59.965729f);
                        path.LineTo(43.0238921f, 97.5342563f);
                        path.CubicTo(41.6587026f, 99.9325978f, 41.6587026f, 103.067402f, 43.0238921f, 105.465744f);
                        path.LineTo(64.5928855f, 143.034271f);
                        path.CubicTo(65.9798162f, 145.426228f, 68.6763107f, 146.994582f, 71.4311121f, 147f);
                        path.LineTo(114.568946f, 147f);
                        path.CubicTo(117.323748f, 146.994143f, 120.020241f, 145.426228f, 121.407172f, 143.034271f);
                        path.LineTo(142.976161f, 105.465744f);
                        path.CubicTo(144.34135f, 103.067402f, 144.341209f, 99.9325978f, 142.976161f, 97.5342563f);
                        path.LineTo(121.407172f, 59.965729f);
                        path.CubicTo(120.020241f, 57.5737917f, 117.323748f, 56.0054182f, 114.568946f, 56f);
                        path.LineTo(71.4311121f, 56f);
                        path.Close();

                        // draw the Xamagon path
                        canvas.DrawPath(path, paint);
                    } // End Using path


                    // ClipDeviceBounds not ClipBounds
                    canvas.DrawLine(0, 0, canvas.ClipDeviceBounds.Width, canvas.ClipDeviceBounds.Height, paint);
                    canvas.DrawLine(0, canvas.ClipDeviceBounds.Height, canvas.ClipDeviceBounds.Width, 0, paint);

                    canvas.DrawLine(0 + 1, 0, 0 + 1, canvas.ClipDeviceBounds.Height, paint);

                    canvas.DrawLine(0, surface.Canvas.ClipDeviceBounds.Height / 2, canvas.ClipDeviceBounds.Width, canvas.ClipDeviceBounds.Height / 2, paint);

                    canvas.DrawLine(canvas.ClipDeviceBounds.Width - 1, 0 + 1, canvas.ClipDeviceBounds.Width - 1, canvas.ClipDeviceBounds.Height, paint);
                } // End Using paint


                // Your drawing code goes here.
                // surface.Snapshot().Encode(SKImageEncodeFormat.Webp, 80);
                // SKData p = surface.Snapshot().Encode();
                SKData p = surface.Snapshot().Encode(SKImageEncodeFormat.Png, 80);
                // p.SaveTo()



                using (System.IO.MemoryStream ms = new System.IO.MemoryStream(p.ToArray()))
                {
                    this.pictureBox1.Image = System.Drawing.Image.FromStream(ms);
                } // End Using ms

                System.IO.File.WriteAllBytes(MapProjectPath("~testme.png"), p.ToArray());
            } // End Using surface

            // this.Close();
        } // End Sub
Exemple #35
0
 public static SKMaskFilter CreateBlur(SKBlurStyle blurStyle, float sigma, SKRect occluder)
 {
     return(CreateBlur(blurStyle, sigma, occluder, SKBlurMaskFilterFlags.None));
 }
Exemple #36
0
 public void ClipRect(SKRect rect, SKRegionOperation operation = SKRegionOperation.Intersect, bool antialias = false)
 {
     SkiaApi.sk_canvas_clip_rect_with_operation (Handle, ref rect, operation, antialias);
 }
Exemple #37
0
 public static SKMaskFilter CreateBlur(SKBlurStyle blurStyle, float sigma, SKRect occluder, SKBlurMaskFilterFlags flags)
 {
     return(GetObject <SKMaskFilter> (SkiaApi.sk_maskfilter_new_blur_with_flags(blurStyle, sigma, ref occluder, flags)));
 }
Exemple #38
0
        public void DrawBitmapLattice(SKBitmap bitmap, int[] xDivs, int[] yDivs, SKRect dst, SKPaint paint = null)
        {
            if (bitmap == null)
                throw new ArgumentNullException (nameof (bitmap));
            if (xDivs == null)
                throw new ArgumentNullException (nameof (xDivs));
            if (yDivs == null)
                throw new ArgumentNullException (nameof (yDivs));

            SkiaApi.sk_canvas_draw_bitmap_lattice (Handle, bitmap.Handle, xDivs, xDivs.Length, yDivs, yDivs.Length, ref dst, paint == null ? IntPtr.Zero : paint.Handle);
        }
Exemple #39
0
        private void ReadElement(XElement e, SKCanvas canvas, SKPaint stroke, SKPaint fill)
        {
            // transform matrix
            var transform = ReadTransform(e.Attribute("transform")?.Value ?? string.Empty);

            canvas.Save();
            canvas.Concat(ref transform);

            // SVG element
            var elementName = e.Name.LocalName;
            var isGroup     = elementName == "g";

            // read style
            var style = ReadPaints(e, ref stroke, ref fill, isGroup);

            // parse elements
            switch (elementName)
            {
            case "text":
                if (stroke != null || fill != null)
                {
                    ReadText(e, canvas, stroke?.Clone(), fill?.Clone());
                }
                break;

            case "rect":
                if (stroke != null || fill != null)
                {
                    var x      = ReadNumber(e.Attribute("x"));
                    var y      = ReadNumber(e.Attribute("y"));
                    var width  = ReadNumber(e.Attribute("width"));
                    var height = ReadNumber(e.Attribute("height"));
                    var rx     = ReadNumber(e.Attribute("rx"));
                    var ry     = ReadNumber(e.Attribute("ry"));
                    var rect   = SKRect.Create(x, y, width, height);
                    if (rx > 0 || ry > 0)
                    {
                        if (fill != null)
                        {
                            canvas.DrawRoundRect(rect, rx, ry, fill);
                        }
                        if (stroke != null)
                        {
                            canvas.DrawRoundRect(rect, rx, ry, stroke);
                        }
                    }
                    else
                    {
                        if (fill != null)
                        {
                            canvas.DrawRect(rect, fill);
                        }
                        if (stroke != null)
                        {
                            canvas.DrawRect(rect, stroke);
                        }
                    }
                }
                break;

            case "ellipse":
                if (stroke != null || fill != null)
                {
                    var cx = ReadNumber(e.Attribute("cx"));
                    var cy = ReadNumber(e.Attribute("cy"));
                    var rx = ReadNumber(e.Attribute("rx"));
                    var ry = ReadNumber(e.Attribute("ry"));
                    if (fill != null)
                    {
                        canvas.DrawOval(cx, cy, rx, ry, fill);
                    }
                    if (stroke != null)
                    {
                        canvas.DrawOval(cx, cy, rx, ry, stroke);
                    }
                }
                break;

            case "circle":
                if (stroke != null || fill != null)
                {
                    var cx = ReadNumber(e.Attribute("cx"));
                    var cy = ReadNumber(e.Attribute("cy"));
                    var rr = ReadNumber(e.Attribute("r"));
                    if (fill != null)
                    {
                        canvas.DrawCircle(cx, cy, rr, fill);
                    }
                    if (stroke != null)
                    {
                        canvas.DrawCircle(cx, cy, rr, stroke);
                    }
                }
                break;

            case "path":
                if (stroke != null || fill != null)
                {
                    var d = e.Attribute("d")?.Value;
                    if (!string.IsNullOrWhiteSpace(d))
                    {
                        var path = SKPath.ParseSvgPathData(d);
                        if (fill != null)
                        {
                            canvas.DrawPath(path, fill);
                        }
                        if (stroke != null)
                        {
                            canvas.DrawPath(path, stroke);
                        }
                    }
                }
                break;

            case "polygon":
            case "polyline":
                if (stroke != null || fill != null)
                {
                    var close = elementName == "polygon";
                    var p     = e.Attribute("points")?.Value;
                    if (!string.IsNullOrWhiteSpace(p))
                    {
                        var path = ReadPolyPath(p, close);
                        if (fill != null)
                        {
                            canvas.DrawPath(path, fill);
                        }
                        if (stroke != null)
                        {
                            canvas.DrawPath(path, stroke);
                        }
                    }
                }
                break;

            case "g":
                if (e.HasElements)
                {
                    // get current group opacity
                    float groupOpacity = ReadOpacity(style);
                    if (groupOpacity != 1.0f)
                    {
                        var opacity      = (byte)(255 * groupOpacity);
                        var opacityPaint = new SKPaint {
                            Color = SKColors.Black.WithAlpha(opacity)
                        };

                        // apply the opacity
                        canvas.SaveLayer(opacityPaint);
                    }

                    foreach (var gElement in e.Elements())
                    {
                        ReadElement(gElement, canvas, stroke?.Clone(), fill?.Clone());
                    }

                    // restore state
                    if (groupOpacity != 1.0f)
                    {
                        canvas.Restore();
                    }
                }
                break;

            case "use":
                if (e.HasAttributes)
                {
                    var href = ReadHref(e);
                    if (href != null)
                    {
                        // TODO: copy/process other attributes

                        var x            = ReadNumber(e.Attribute("x"));
                        var y            = ReadNumber(e.Attribute("y"));
                        var useTransform = SKMatrix.MakeTranslation(x, y);

                        canvas.Save();
                        canvas.Concat(ref useTransform);

                        ReadElement(href, canvas, stroke?.Clone(), fill?.Clone());

                        canvas.Restore();
                    }
                }
                break;

            case "line":
                if (stroke != null)
                {
                    var x1 = ReadNumber(e.Attribute("x1"));
                    var x2 = ReadNumber(e.Attribute("x2"));
                    var y1 = ReadNumber(e.Attribute("y1"));
                    var y2 = ReadNumber(e.Attribute("y2"));
                    canvas.DrawLine(x1, y1, x2, y2, stroke);
                }
                break;

            case "switch":
                if (e.HasElements)
                {
                    foreach (var ee in e.Elements())
                    {
                        var requiredFeatures   = ee.Attribute("requiredFeatures");
                        var requiredExtensions = ee.Attribute("requiredExtensions");
                        var systemLanguage     = ee.Attribute("systemLanguage");

                        // TODO: evaluate requiredFeatures, requiredExtensions and systemLanguage
                        var isVisible =
                            requiredFeatures == null &&
                            requiredExtensions == null &&
                            systemLanguage == null;

                        if (isVisible)
                        {
                            ReadElement(ee, canvas, stroke?.Clone(), fill?.Clone());
                        }
                    }
                }
                break;

            case "defs":
            case "title":
            case "desc":
            case "description":
                // already read earlier
                break;

            default:
                LogOrThrow($"SVG element '{elementName}' is not supported");
                break;
            }

            // restore matrix
            canvas.Restore();
        }
		public SKCanvas BeginRecording (SKRect rect)
		{
			return GetObject<SKCanvas> (SkiaApi.sk_picture_recorder_begin_recording (Handle, ref rect), false);
		}
Exemple #41
0
 public static SKRect Intersect(SKRect a, SKRect b)
 {
     if (!a.IntersectsWithInclusive(b))
     {
         return Empty;
     }
     return new SKRect(
         Math.Max(a.left, b.left),
         Math.Max(a.top, b.top),
         Math.Min(a.right, b.right),
         Math.Min(a.bottom, b.bottom));
 }
 public SKCanvas BeginRecording(SKRect cullRect)
 {
     return(GetObject <SKCanvas> (SkiaApi.sk_picture_recorder_begin_recording(Handle, &cullRect), false));
 }
Exemple #43
0
 public static void MapRect(ref SKMatrix matrix, out SKRect dest, ref SKRect source)
 {
     SkiaApi.sk_matrix_map_rect(ref matrix, out dest, ref source);
 }
Exemple #44
0
 public bool IntersectsWith(SKRect rect)
 {
     return !((left >= rect.right) || (right <= rect.left) ||
             (top >= rect.bottom) || (bottom <= rect.top));
 }
Exemple #45
0
 public bool IntersectsWithInclusive(SKRect rect)
 {
     return !((left > rect.right) || (right < rect.left) ||
              (top > rect.bottom) || (bottom < rect.top));
 }
Exemple #46
0
 public void Union(SKRect rect)
 {
     this = SKRect.Union(this, rect);
 }
Exemple #47
0
 public bool Contains(SKRect rect)
 {
     return
         (left <= rect.left) && (right >= rect.right) &&
         (top <= rect.top) && (bottom >= rect.bottom);
 }
Exemple #48
0
 public void DrawOval(SKRect rect, SKPaint paint)
 {
     if (paint == null)
         throw new ArgumentNullException (nameof (paint));
     SkiaApi.sk_canvas_draw_oval (Handle, ref rect, paint.Handle);
 }
Exemple #49
0
 public static SKRect Union(SKRect a, SKRect b)
 {
     return new SKRect(
         Math.Min(a.left, b.left),
         Math.Min(a.top, b.top),
         Math.Max(a.right, b.right),
         Math.Max(a.bottom, b.bottom));
 }
Exemple #50
0
 public static SKRect Inflate(SKRect rect, float x, float y)
 {
     var r = new SKRect(rect.left, rect.top, rect.right, rect.bottom);
     r.Inflate(x, y);
     return r;
 }
Exemple #51
0
        public void DrawImageLattice(SKImage image, int[] xDivs, int[] yDivs, SKRect dst, SKPaint paint = null)
        {
            if (image == null)
                throw new ArgumentNullException (nameof (image));
            if (xDivs == null)
                throw new ArgumentNullException (nameof (xDivs));
            if (yDivs == null)
                throw new ArgumentNullException (nameof (yDivs));

            SkiaApi.sk_canvas_draw_image_lattice (Handle, image.Handle, xDivs, xDivs.Length, yDivs, yDivs.Length, ref dst, paint == null ? IntPtr.Zero : paint.Handle);
        }
Exemple #52
0
        public static SKRectI Round(SKRect value)
        {
            int x, y, r, b;
            checked
            {
                x = (int)Math.Round(value.Left);
                y = (int)Math.Round(value.Top);
                r = (int)Math.Round(value.Right);
                b = (int)Math.Round(value.Bottom);
            }

            return new SKRectI(x, y, r, b);
        }
Exemple #53
0
        public static SKRectI Truncate(SKRect value)
        {
            int x, y, r, b;
            checked
            {
                x = (int)value.Left;
                y = (int)value.Top;
                r = (int)value.Right;
                b = (int)value.Bottom;
            }

            return new SKRectI(x, y, r, b);
        }
Exemple #54
0
 public int SaveLayer(SKRect limit, SKPaint paint)
 {
     return SkiaApi.sk_canvas_save_layer (Handle, ref limit, paint == null ? IntPtr.Zero : paint.Handle);
 }
Exemple #55
0
 public bool GetClipBounds(ref SKRect bounds)
 {
     return SkiaApi.sk_canvas_get_clip_bounds(Handle, ref bounds);
 }
Exemple #56
0
 public void DrawRoundRect(SKRect rect, float rx, float ry, SKPaint paint)
 {
     if (paint == null)
                 throw new ArgumentNullException (nameof (paint));
         SkiaApi.sk_canvas_draw_round_rect (Handle, ref rect, rx, ry, paint.Handle);
 }
Exemple #57
0
 public SKRect MapRect(SKRect source)
 {
     SKRect result;
     MapRect(ref this, out result, ref source);
     return result;
 }
Exemple #58
0
 public void Intersect(SKRect rect)
 {
     this = SKRect.Intersect(this, rect);
 }
Exemple #59
-1
 public void DrawImage(SKImage image, SKRect source, SKRect dest, SKPaint paint = null)
 {
     if (image == null)
         throw new ArgumentNullException (nameof (image));
     SkiaApi.sk_canvas_draw_image_rect (Handle, image.Handle, ref source, ref dest, paint == null ? IntPtr.Zero : paint.Handle);
 }
Exemple #60
-1
        public void DrawImageNinePatch(SKImage image, SKRectI center, SKRect dst, SKPaint paint = null)
        {
            if (image == null)
                throw new ArgumentNullException (nameof (image));
            // the "center" rect must fit inside the image "rect"
            if (!SKRect.Create (image.Width, image.Height).Contains (center))
                throw new ArgumentOutOfRangeException (nameof (center));

            var xDivs = new [] { center.Left, center.Right };
            var yDivs = new [] { center.Top, center.Bottom };
            DrawImageLattice (image, xDivs, yDivs, dst, paint);
        }