コード例 #1
0
        void DisplayClipOp(SKCanvas canvas, SKRect rect, SKClipOperation clipOp)
        {
            float textSize = textPaint.TextSize;

            canvas.DrawText(clipOp.ToString(), rect.MidX, rect.Top + textSize, textPaint);
            rect.Top += textSize;

            float radius  = 0.9f * Math.Min(rect.Width / 3, rect.Height / 2);
            float xCenter = rect.MidX;
            float yCenter = rect.MidY;

            canvas.Save();

            using (SKPath path1 = new SKPath())
            {
                path1.AddCircle(xCenter - radius / 2, yCenter, radius);
                canvas.ClipPath(path1);

                using (SKPath path2 = new SKPath())
                {
                    path2.AddCircle(xCenter + radius / 2, yCenter, radius);
                    canvas.ClipPath(path2, clipOp);

                    canvas.DrawPaint(fillPaint);
                }
            }

            canvas.Restore();
        }
コード例 #2
0
        public override void PreProcess(SKCanvas canvas, SKRect bounds, SKPaint paint)
        {
            // TODO: Lets see whether we can tell Artemis we only support layers
            if (ProfileElement is not Layer layer || !layer.Leds.Any())
            {
                return;
            }

            // Find out how many LEDs to reveal according to the current percentage
            int toReveal = Properties.RoundingFunction.CurrentValue switch
            {
                RoundingFunction.Round => (int)Math.Round(layer.Leds.Count / 100.0 * Math.Min(100, Properties.Percentage.CurrentValue), MidpointRounding.AwayFromZero),
                RoundingFunction.Floor => (int)Math.Floor(layer.Leds.Count / 100.0 * Math.Min(100, Properties.Percentage.CurrentValue)),
                RoundingFunction.Ceiling => (int)Math.Ceiling(layer.Leds.Count / 100.0 * Math.Min(100, Properties.Percentage.CurrentValue)),
                _ => throw new ArgumentOutOfRangeException()
            };

            // If the amount hasn't changed, reuse the last path
            if (toReveal == _lastToReveal && Properties.MaxVisibleLeds == _lastMaxVisible && _clipPath != null)
            {
                canvas.ClipPath(_clipPath);
                return;
            }

            // Order LEDs by their position to create a nice revealing effect from left top right, top to bottom
            List <ArtemisLed> leds = layer.Leds.OrderBy(l => l.AbsoluteRectangle.Top).ThenBy(l => l.AbsoluteRectangle.Left).ToList();
            // Because rendering for effects is 0,0 based, zero out the position of LEDs starting at the top-left
            float offsetX = leds.First().AbsoluteRectangle.Left;
            float offsetY = leds.First().AbsoluteRectangle.Top;

            // Create or reset the path
            if (_clipPath == null)
            {
                _clipPath = new SKPath();
            }
            else
            {
                _clipPath.Reset();
            }

            IEnumerable <ArtemisLed> ledsEnumerable = leds.Take(toReveal);

            if (Properties.LimitVisibleLeds)
            {
                ledsEnumerable = ledsEnumerable.Skip(toReveal - Properties.MaxVisibleLeds);
            }
            foreach (ArtemisLed artemisLed in ledsEnumerable)
            {
                _clipPath.AddRect(SKRect.Create(
                                      artemisLed.AbsoluteRectangle.Left - offsetX,
                                      artemisLed.AbsoluteRectangle.Top - offsetY,
                                      artemisLed.AbsoluteRectangle.Width,
                                      artemisLed.AbsoluteRectangle.Height));
            }

            canvas.ClipPath(_clipPath);
            _lastMaxVisible = Properties.MaxVisibleLeds;
            _lastToReveal   = toReveal;
        }
コード例 #3
0
        private void DrawShadow(SKCanvas canvas)
        {
            var pancake = Element as PancakeView;

            if (pancake.Shadow != null)
            {
                SKPath path;
                if (pancake.Sides != 4)
                {
                    path = DrawingExtensions.CreatePolygonPath(Control.Geometry.Width, Control.Geometry.Height,
                                                               pancake.Sides, pancake.CornerRadius.TopLeft, pancake.OffsetAngle);
                }
                else
                {
                    var left = Control.Geometry.Left - _skCanvasView.Geometry.Left;
                    var top  = Control.Geometry.Top - _skCanvasView.Geometry.Top;
                    path = DrawingExtensions.CreateRoundedRectPath(left, top, left + Control.Geometry.Width, top + Control.Geometry.Height, pancake.CornerRadius);
                }

                using (var paint = new SKPaint())
                {
                    paint.IsAntialias = true;
                    paint.Style       = SKPaintStyle.StrokeAndFill;

                    var shadow           = pancake.Shadow;
                    var scaledOffsetX    = Forms.ConvertToScaledPixel(shadow.Offset.X);
                    var scaledOffsetY    = Forms.ConvertToScaledPixel(shadow.Offset.Y);
                    var scaledBlurRadius = Forms.ConvertToScaledPixel(shadow.BlurRadius);

                    canvas.Save();
                    canvas.ClipPath(path, SKClipOperation.Difference, true);
                    paint.ImageFilter = SKImageFilter.CreateDropShadow(
                        scaledOffsetX,
                        scaledOffsetY,
                        scaledBlurRadius,
                        scaledBlurRadius,
                        shadow.Color.MultiplyAlpha(shadow.Opacity).ToNative().ToSKColor(),
                        SKDropShadowImageFilterShadowMode.DrawShadowOnly);
                    canvas.DrawPath(path, paint);
                    canvas.Restore();

                    canvas.Save();
                    canvas.ClipPath(path, SKClipOperation.Intersect, true);
                    canvas.DrawPath(path, paint);
                    canvas.Restore();
                }
            }
        }
コード例 #4
0
        public override void Draw(SKCanvas canvas, RectangleF dirtyRect)
        {
            canvas.Clear(Color.Transparent.ToSKColor());
            if (TypedVirtualView == null || drawMapper == null)
            {
                return;
            }
            canvas.Save();
            var layers  = LayerDrawingOrder();
            var padding = this.GetPadding();
            var rect    = dirtyRect.ApplyPadding(padding);

            foreach (var layer in layers)
            {
                drawMapper.DrawLayer(canvas, rect, this, TypedVirtualView, layer);
            }

            var clipShape = VirtualView?.GetClipShape() ?? VirtualView?.GetBorder();

            if (clipShape != null)
            {
                canvas.ClipPath(clipShape.PathForBounds(rect).ToSKPath());
            }

            drawMapper.DrawLayer(canvas, rect, this, TypedVirtualView, SkiaEnvironmentKeys.Border);

            canvas.Restore();
        }
コード例 #5
0
        void OnCanvasViewPaintSurface(object sender, SKPaintSurfaceEventArgs args)
        {
            SKImageInfo info    = args.Info;
            SKSurface   surface = args.Surface;
            SKCanvas    canvas  = surface.Canvas;

            canvas.Clear();

            // Set transform to center and enlarge clip path to window height
            SKRect bounds;

            path.GetTightBounds(out bounds);

            canvas.Translate(info.Width / 2, info.Height / 2);
            canvas.Scale((0.5f * info.Height / bounds.Height) * -1);
            canvas.Translate(-bounds.MidX, -bounds.MidY);

            // Set the clip path
            canvas.ClipPath(path, SKClipOperation.Difference);

            // Reset transforms
            canvas.ResetMatrix();
            using (SKPaint paint2 = new SKPaint())
            {
                paint2.Style = SKPaintStyle.Fill;
                paint2.Color = SKColors.Green.WithAlpha(0x50);
                canvas.DrawPaint(paint2);
            }
        }
コード例 #6
0
        private void OnCanvasViewPaintSurface(object sender, SKPaintSurfaceEventArgs e)
        {
            SKImageInfo info    = e.Info;
            SKSurface   surface = e.Surface;
            SKCanvas    canvas  = surface.Canvas;

            canvas.Clear();

            if (_pathToClip != null)
            {
                // Crop canvas before drawing image
                canvas.ClipPath(_pathToClip);
            }

            canvas.DrawBitmap(_originalBitmap, info.Rect);

            if (_pathToClip != null)
            {
                // Get cropped image byte array
                var snap = surface.Snapshot();
                var data = snap.Encode();
                _bytearray = data.ToArray();

                ManualCropView.IsVisible       = false;
                CropButton.IsVisible           = false;
                DisplayCroppedButton.IsVisible = true;
            }
        }
コード例 #7
0
        void OnCanvasViewPaintSurface(object sender, SKPaintSurfaceEventArgs args)
        {
            SKImageInfo info    = args.Info;
            SKSurface   surface = args.Surface;
            SKCanvas    canvas  = surface.Canvas;

            canvas.Clear();

            // Set transform to center and enlarge clip path to window height
            SKRect bounds;

            keyholePath.GetTightBounds(out bounds);

            canvas.Translate(info.Width / 2, info.Height / 2);
            canvas.Scale(0.98f * info.Height / bounds.Height);
            canvas.Translate(-bounds.MidX, -bounds.MidY);

            // Set the clip path
            canvas.ClipPath(keyholePath);

            // Reset transforms
            canvas.ResetMatrix();

            // Display monkey to fill height of window but maintain aspect ratio
            canvas.DrawBitmap(bitmap,
                              new SKRect((info.Width - info.Height) / 2, 0,
                                         (info.Width + info.Height) / 2, info.Height));
        }
コード例 #8
0
        public void Draw(SKCanvas c, SKPath path, SKPaint paint, SKRect rect)
        {
            if (GradientColors == null)
            {
                return;
            }
            int save = c.Save();

            c.ClipPath(path);
            using (var gradient = SKShader.CreateLinearGradient(
                       SKPoint.Empty,
                       new SKPoint(rect.Width,
                                   rect.Height),
                       GradientColors,
                       ColorPos,
                       SKShaderTileMode.Mirror))
            {
                var previousStyle = paint.Style;
                paint.Style  = SKPaintStyle.Fill;
                paint.Shader = gradient;
                c.DrawPath(path, paint);
                paint.Style = previousStyle;
            }

            c.RestoreToCount(save);
        }
コード例 #9
0
 public void Fill(SKCanvas canvas, SKPath path)
 {
     using (var paint = new SKPaint()
     {
         IsAntialias = true,
         Style = SKPaintStyle.Fill,
     })
     {
         canvas.Save();
         try
         {
             using (var img = SKImage.FromBitmap(Source))
             {
                 paint.Color = SKColors.White.WithAlpha((byte)(this.Opacity * 255));
                 canvas.ClipPath(path);
                 canvas.DrawImage(img, path.Bounds, paint);
             }
         }
         catch (Exception e)
         {
             using (var errorPaint = new SKPaint
             {
                 Color = SKColors.Red,
                 Style = SKPaintStyle.Fill,
             })
             {
                 canvas.DrawRect(path.Bounds, errorPaint);
                 errorPaint.Color = SKColors.White;
                 canvas.DrawText(e.Message, path.Bounds.MidX, path.Bounds.MidY, errorPaint);
             }
         }
         canvas.Restore();
     }
 }
コード例 #10
0
 public void DrawHole(SKCanvas canvas, SKRect rect, float scale = 1)
 {
     using (SKPath path = new SKPath())
     {
         path.AddCircle(rect.Left + rect.Width / 2, rect.Top + rect.Height / 2, rect.Width / 2);
         canvas.ClipPath(path, SKClipOperation.Difference);
     }
 }
コード例 #11
0
        public void Close()
        {
            canvas.ClipPath(clip, SKClipOperation.Intersect, true);
            canvas.DrawImage(SKImage.FromBitmap(noise), new SKPoint(0, 0));
            canvas.DrawImage(surface.Snapshot(), new SKPoint(0, 0), paint);

            canvas.Restore();
        }
コード例 #12
0
        /// <summary>
        /// Draws the provided path in filled mode with the provided color and alpha.
        /// Special thanks to Angelo Suzuki (https://github.com/tinsukE) for this.
        protected void DrawFilledPath(SKCanvas c, SKPath filledPath, SKColor fillColor, byte fillAlpha)
        {
            int save = c.Save();

            c.ClipPath(filledPath);
            c.DrawColor(fillColor.WithAlpha(fillAlpha), SKBlendMode.SrcOver);
            c.RestoreToCount(save);
        }
コード例 #13
0
ファイル: SKSvgRenderer.cs プロジェクト: jorik041/Svg.Skia
        internal void SetClipPath(SvgVisualElement svgVisualElement, CompositeDisposable disposable)
        {
            var skPathClip = SkiaUtil.GetSvgVisualElementClipPath(svgVisualElement, disposable);

            if (skPathClip != null && !skPathClip.IsEmpty)
            {
                bool antialias = SkiaUtil.IsAntialias(svgVisualElement);
                _skCanvas.ClipPath(skPathClip, SKClipOperation.Intersect, antialias);
            }
        }
コード例 #14
0
ファイル: SkiaControl.cs プロジェクト: AndreAbrantes/Comet
        public static void ClipCanvas(SKCanvas canvas, RectangleF dirtyRect, SkiaControl control, View view)
        {
            var border    = control?.GetBorder();
            var clipShape = control?.GetClipShape() ?? border;

            if (clipShape != null)
            {
                canvas.ClipPath(clipShape.PathForBounds(dirtyRect).ToSKPath());
            }
        }
コード例 #15
0
ファイル: ScaleSlider.cs プロジェクト: TheCodeSage/XamForms
        void DrawClippingMask(SKCanvas canvas, SKImageInfo info)
        {
            //Move clipping mask
            var xPos = sliderPosition - clipPath.TightBounds.MidX;

            clipPath.Transform(SKMatrix.MakeTranslation(xPos, 0));

            //Draw clipping mask
            canvas.ClipPath(clipPath, SKClipOperation.Difference, true);
        }
コード例 #16
0
        private void DrawBorder(SKCanvas canvas)
        {
            var pancake = Element as PancakeView;

            if (pancake.Border != null && pancake.Border.Thickness != default)
            {
                using (var paint = new SKPaint())
                {
                    var border = pancake.Border;
                    paint.Style       = SKPaintStyle.Stroke;
                    paint.Color       = border.Color.ToNative().ToSKColor();
                    paint.StrokeWidth = Forms.ConvertToScaledPixel(border.Thickness);
                    paint.IsAntialias = true;

                    SKPath path;
                    if (pancake.Sides != 4)
                    {
                        path = DrawingExtensions.CreatePolygonPath(Control.Geometry.Width, Control.Geometry.Height,
                                                                   pancake.Sides, pancake.CornerRadius.TopLeft, pancake.OffsetAngle);
                    }
                    else
                    {
                        var left = Control.Geometry.Left - _skCanvasView.Geometry.Left;
                        var top  = Control.Geometry.Top - _skCanvasView.Geometry.Top;
                        path = DrawingExtensions.CreateRoundedRectPath(left, top, left + Control.Geometry.Width, top + Control.Geometry.Height, pancake.CornerRadius);
                    }

                    if (border.DashPattern.Pattern != null &&
                        border.DashPattern.Pattern.Length > 0 &&
                        (border.DashPattern.Pattern.Length % 2 == 0 || border.DashPattern.Pattern.Length == 1))
                    {
                        var items = border.DashPattern.Pattern.Select(x => Convert.ToSingle(x)).ToList();

                        if (items.Count == 1)
                        {
                            items.Add(items[0]);
                        }

                        paint.PathEffect = SKPathEffect.CreateDash(items.ToArray(), 0);
                    }

                    if (border.GradientStops != null && border.GradientStops.Any())
                    {
                        var startPoint       = new SKPoint((float)(border.GradientStartPoint.X * Control.Geometry.Width), (float)(border.GradientStartPoint.Y * Control.Geometry.Height));
                        var endPoint         = new SKPoint((float)(border.GradientEndPoint.X * Control.Geometry.Width), (float)(border.GradientEndPoint.Y * Control.Geometry.Height));
                        var orderedStops     = border.GradientStops.OrderBy(x => x.Offset).ToList();
                        var gradientColors   = orderedStops.Select(x => x.Color.ToNative().ToSKColor()).ToArray();
                        var gradientColorPos = orderedStops.Select(x => x.Offset).ToArray();
                        paint.Shader = SKShader.CreateLinearGradient(startPoint, endPoint, gradientColors, gradientColorPos, SKShaderTileMode.Clamp);
                    }
                    canvas.ClipPath(path, SKClipOperation.Intersect, true);
                    canvas.DrawPath(path, paint);
                }
            }
        }
コード例 #17
0
        private void ImageSkiaCanvas_PaintSurface(object sender, SkiaSharp.Views.Forms.SKPaintSurfaceEventArgs args)
        {
            SKImageInfo info    = args.Info;
            SKSurface   surface = args.Surface;
            SKCanvas    canvas  = surface.Canvas;

            canvas.Clear();

            SKRect imageRect = new SKRect(0, 0, info.Width, info.Height);

            // render out the bitmap
            SKRect outgoingImageRect;

            if (transitionValue >= 1)
            {
                outgoingImageRect = new SKRect(0 - (float)outgoingOffset, 0, info.Width, info.Height);
            }
            else
            {
                outgoingImageRect = new SKRect(0, 0, info.Width, info.Height);
            }

            canvas.DrawBitmap(currentBitmap, outgoingImageRect, BitmapStretch.AspectFill);

            if (transitionValue <= 0)
            {
                return;
            }

            // draw our clipping path
            if (offscreenBitmap != null)
            {
                // animate int the rect that the image is being rendered to
                int    movementAmount = 600;
                float  offset         = (float)(movementAmount - (movementAmount * (transitionValue / 2)));
                SKRect incomingRect   = new SKRect(0, 0, info.Width + offset, info.Height);

                // draw the faded version of the image
                using (SKPaint transparentPaint = new SKPaint())
                {
                    var opacity = Math.Max((transitionValue - .5) * .5, 0);
                    transparentPaint.Color = transparentPaint.Color.WithAlpha((byte)(0xFF * opacity));
                    canvas.DrawBitmap(
                        bitmap: offscreenBitmap,
                        dest: incomingRect,
                        stretch: BitmapStretch.AspectFill,
                        paint: transparentPaint);
                }

                var clipPath = CalculateClipPath(info, transitionValue);
                canvas.ClipPath(clipPath, SKClipOperation.Intersect);
                canvas.DrawBitmap(offscreenBitmap, incomingRect, BitmapStretch.AspectFill);
            }
        }
コード例 #18
0
        static void PrepBitmap(SKCanvas bitmapCanvas, int bitmapSize)
        {
            // Set clipping path based on bitmap size
            using (SKPath bitmapClipPath = new SKPath())
            {
                bitmapClipPath.AddCircle(bitmapSize / 2, bitmapSize / 2, bitmapSize / 2);
                bitmapCanvas.ClipPath(bitmapClipPath);
            }

            // Color the bitmap background
            bitmapCanvas.Clear(backgroundColor);
        }
コード例 #19
0
        void OnCanvasViewPaintSurface(object sender, SKPaintSurfaceEventArgs args)
        {
            SKImageInfo info    = args.Info;
            SKSurface   surface = args.Surface;
            SKCanvas    canvas  = surface.Canvas;

            canvas.Clear();

            float size   = Math.Min(info.Width, info.Height);
            float radius = 0.4f * size;
            float offset = size / 2 - radius;

            // Translate to center
            canvas.Translate(info.Width / 2, info.Height / 2);

            using (SKPath path = new SKPath())
            {
                path.AddCircle(-offset, -offset, radius);
                canvas.ClipPath(path, SKClipOperation.Intersect);

                path.Reset();
                path.AddCircle(-offset, offset, radius);
                canvas.ClipPath(path, SKClipOperation.Intersect);

                path.Reset();
                path.AddCircle(offset, -offset, radius);
                canvas.ClipPath(path, SKClipOperation.Intersect);

                path.Reset();
                path.AddCircle(offset, offset, radius);
                canvas.ClipPath(path, SKClipOperation.Intersect);

                using (SKPaint paint = new SKPaint())
                {
                    paint.Style = SKPaintStyle.Fill;
                    paint.Color = SKColors.Blue;
                    canvas.DrawPaint(paint);
                }
            }
        }
コード例 #20
0
ファイル: ToolOval.cs プロジェクト: jensbrak/Phiddle
        protected override void DrawMarks(SKCanvas c)
        {
            // Get the rect vectors
            var pTR         = new SKPoint(p1.X, p0.Y);
            var pBL         = new SKPoint(p0.X, p1.Y);
            var vHorizontal = new SKPoint(p1.X - p0.X, 0);
            var vVertical   = new SKPoint(0, p1.Y - p0.Y);

            // Clip path as defined by the oval
            var clipBounds = new SKRect(
                frame.Bounds.Left + 3,
                frame.Bounds.Top + 3,
                frame.Bounds.Right - 3,
                frame.Bounds.Bottom - 3);
            var clipPath = new SKPath();

            clipPath.AddOval(clipBounds);

            // Draw all visible marks
            foreach (var mark in marks)
            {
                if (!mark.Visible)
                {
                    continue;
                }

                // Clip all marks but Endpoints (they're the bounding box)
                if (mark.MarkId != MarkId.Endpoint)
                {
                    c.Save();
                    c.ClipPath(clipPath);
                }

                foreach (var m in mark.Pos)
                {
                    // Positions relative the the sides
                    var v0 = p0.Pos + vHorizontal.Scale(m);
                    var v1 = pBL + vHorizontal.Scale(m);
                    var h0 = p0.Pos + vVertical.Scale(m);
                    var h1 = pTR + vVertical.Scale(m);

                    // Draw them
                    c.DrawLine(v0, v1, mark.PaintMark);
                    c.DrawLine(h0, h1, mark.PaintMark);
                }

                if (mark.MarkId != MarkId.Endpoint)
                {
                    c.Restore();
                }
            }
        }
コード例 #21
0
        private void CanvasView_PaintSurface(object sender, SKPaintSurfaceEventArgs e)
        {
            SKImageInfo info    = e.Info;
            SKSurface   surface = e.Surface;
            SKCanvas    canvas  = surface.Canvas;

            canvas.Clear();

            if (lastSize.Width != info.Width || lastSize.Height != info.Height)
            {
                lastSize.Width  = info.Width;
                lastSize.Height = info.Height;

                radius = (float)Math.Min(lastSize.Width, lastSize.Height);

                isChanged = true;
            }
            if (isChanged)
            {
                circleMaskPath = CreateCircleMaskPath(info.Width, info.Height);
                isChanged      = false;
            }
            wavePath = CreateWaveMaskPath(info.Width, info.Height, radius / 5 / 2 / 2 / 2, transX, transY, 5);

            if (wavePaint == null)
            {
                wavePaint = new SKPaint
                {
                    Style = SKPaintStyle.Fill,
                    Color = FullColor.ToSKColor()
                };
            }


            SKPath cirlePath = new SKPath();

            cirlePath.AddCircle(info.Width / 2, info.Height / 2, Math.Min(info.Width, info.Height) / 2);

            canvas.ClipPath(cirlePath);


            canvas.DrawPath(cirlePath, circlePaint);
            canvas.DrawPath(wavePath, wavePaint);
            //canvas.DrawPath(circleMaskPath, circlePaint);

            if (isAnimate == false)
            {
                Animate();
                isAnimate = true;
            }
        }
コード例 #22
0
        /// <summary>
        ///  draws the description text in the center of the pie chart makes most
        /// sense when center-hole is enabled
        /// </summary>
        /// <param name="c"></param>
        partial void DrawCenterText(SKCanvas c)
        {
            var centerText = Chart.CenterText;

            if (Chart.DrawCenterTextEnabled && centerText != null)
            {
                var center = Chart.CenterCircleBox;
                var offset = Chart.CenterTextOffset;

                float x = center.X + offset.X;
                float y = center.Y + offset.Y;

                float innerRadius = Chart.DrawHoleEnabled && !Chart.DrawSlicesUnderHoleEnabled
                        ? Chart.Radius * (Chart.HoleRadius / 100f)
                        : Chart.Radius;

                var holeRect = SKRect.Empty;
                holeRect.Left   = x - innerRadius;
                holeRect.Top    = y - innerRadius;
                holeRect.Right  = x + innerRadius;
                holeRect.Bottom = y + innerRadius;
                var boundingRect = holeRect;

                float radiusPercent = Chart.CenterTextRadiusPercent / 100f;
                if (radiusPercent > 0.0)
                {
                    boundingRect = boundingRect.Inset(
                        (boundingRect.Width - boundingRect.Width * radiusPercent) / 2.0f,
                        (boundingRect.Height - boundingRect.Height * radiusPercent) / 2.0f
                        );
                }
                //float layoutWidth = Utils.getStaticLayoutMaxWidth(mCenterTextLayout);

                c.Save();
                var path = DrawCenterTextPathBuffer;
                path.Reset();
                path.AddOval(holeRect, SKPathDirection.Clockwise);
                c.ClipPath(path);

                using (var layout = new Components.TextLayout()
                {
                    VerticalAlignment = Xamarin.Forms.TextAlignment.Center,
                    HorizontalAlign = Xamarin.Forms.TextAlignment.Center
                })
                {
                    layout.Draw(c, centerText, boundingRect);
                }

                c.Restore();
            }
        }
コード例 #23
0
        /// <summary>
        ///     Opens the render context using the dimensions of the provided path
        /// </summary>
        public void Open(SKPath path, Folder?parent)
        {
            if (_disposed)
            {
                throw new ObjectDisposedException("Renderer");
            }

            if (IsOpen)
            {
                throw new ArtemisCoreException("Cannot open render context because it is already open");
            }

            if (path.Bounds != _lastBounds || (parent != null && parent.Bounds != _lastParentBounds))
            {
                Invalidate();
            }

            if (!_valid || Canvas == null)
            {
                SKRect pathBounds = path.Bounds;
                int    width      = (int)pathBounds.Width;
                int    height     = (int)pathBounds.Height;

                Bitmap = new SKBitmap(width, height);
                Path   = new SKPath(path);
                Canvas = new SKCanvas(Bitmap);
                Path.Transform(SKMatrix.CreateTranslation(pathBounds.Left * -1, pathBounds.Top * -1));

                TargetLocation = new SKPoint(pathBounds.Location.X, pathBounds.Location.Y);
                if (parent != null)
                {
                    TargetLocation -= parent.Bounds.Location;
                }

                Canvas.ClipPath(Path);

                _lastParentBounds = parent?.Bounds ?? new SKRect();
                _lastBounds       = path.Bounds;
                _valid            = true;
            }

            Paint = new SKPaint();

            Canvas.Clear();
            Canvas.Save();

            IsOpen = true;
        }
コード例 #24
0
        internal override void InternalRender(SKCanvas canvas, SKImageInfo canvasInfo, SKPath path, SKPaint paint)
        {
            // We don't want translations on this canvas because that'll displace the LEDs, translations are applied to the points of each LED instead
            Layer.ExcludeCanvasFromTranslation(canvas, true);

            if (Layer.General.ResizeMode == LayerResizeMode.Normal)
            {
                // Apply a translated version of the shape as the clipping mask
                SKPath shapePath = new SKPath(Layer.LayerShape.Path);
                Layer.IncludePathInTranslation(shapePath, true);
                canvas.ClipPath(shapePath);
            }

            using SKPath pointsPath = new SKPath();
            using SKPaint ledPaint  = new SKPaint();
            foreach (ArtemisLed artemisLed in Layer.Leds)
            {
                pointsPath.AddPoly(new[]
                {
                    new SKPoint(0, 0),
                    new SKPoint(artemisLed.AbsoluteRenderRectangle.Left - Layer.Bounds.Left, artemisLed.AbsoluteRenderRectangle.Top - Layer.Bounds.Top)
                });
            }

            Layer.ExcludePathFromTranslation(pointsPath, true);
            SKPoint[] points = pointsPath.Points;
            for (int index = 0; index < Layer.Leds.Count; index++)
            {
                ArtemisLed artemisLed  = Layer.Leds[index];
                SKPoint    renderPoint = points[index * 2 + 1];
                if (!float.IsFinite(renderPoint.X) || !float.IsFinite(renderPoint.Y))
                {
                    continue;
                }

                // Let the brush determine the color
                ledPaint.Color = GetColor(artemisLed, renderPoint);

                SKRect ledRectangle = SKRect.Create(
                    artemisLed.AbsoluteRenderRectangle.Left - Layer.Bounds.Left,
                    artemisLed.AbsoluteRenderRectangle.Top - Layer.Bounds.Top,
                    artemisLed.AbsoluteRenderRectangle.Width,
                    artemisLed.AbsoluteRenderRectangle.Height
                    );

                canvas.DrawRect(ledRectangle, ledPaint);
            }
        }
コード例 #25
0
        public override void Awake(NSObject context)
        {
            base.Awake(context);

            var scale = WKInterfaceDevice.CurrentDevice.ScreenScale;

            var bitmap = new SKBitmap((int)(ContentFrame.Width * scale), (int)(ContentFrame.Height * scale));

            var colors = new[] { SKColors.Cyan, SKColors.Magenta, SKColors.Yellow, SKColors.Cyan };
            var center = new SKPoint(bitmap.Width / 2, bitmap.Height / 2);

            using (var canvas = new SKCanvas(bitmap))
            {
                canvas.Clear(SKColors.Transparent);

                using (var path = new SKPath())
                {
                    path.AddRoundedRect(new SKRect(5, 5, bitmap.Width - 5, bitmap.Height - 5), 5, 5);
                    canvas.ClipPath(path);
                }

                using (var paint = new SKPaint())
                    using (var gradient = SKShader.CreateSweepGradient(center, colors, null))
                    {
                        paint.IsAntialias = true;
                        paint.Shader      = gradient;
                        canvas.DrawPaint(paint);
                        paint.Shader = null;
                    }

                using (var paint = new SKPaint())
                    using (var tf = SKTypeface.FromFamilyName("San Fransisco"))
                    {
                        paint.IsAntialias = true;
                        paint.Color       = SKColors.DarkBlue;
                        paint.TextSize    = (float)(20 * scale);
                        paint.TextAlign   = SKTextAlign.Center;
                        paint.Typeface    = tf;

                        canvas.DrawText("SkiaSharp", center.X, (center.Y / 2) + (paint.TextSize / 2), paint);
                    }
            }

            var image = bitmap.ToUIImage(scale, UIKit.UIImageOrientation.Up);

            imageView.SetImage(image);
        }
コード例 #26
0
        private async void HandlePaintCanvas(object sender, SKPaintSurfaceEventArgs e)
        {
            SKImageInfo info   = e.Info;
            SKCanvas    canvas = e.Surface.Canvas;

            canvas.Clear();
            if (_doSave)
            {
                using (var hole = new SKPath()) {
                    hole.AddCircle(info.Width / 2, info.Height / 2, info.Width / 3);
                    canvas.ClipPath(hole, antialias: true);
                }
            }
            canvas.SetMatrix(_m);
            //Draw ball image
            SKSize imgSize    = new SKSize(_bitmap.Width, _bitmap.Height);
            SKRect aspectRect = SKRect.Create(info.Width, info.Height).AspectFit(imgSize);

            canvas.DrawBitmap(_bitmap, aspectRect);
            if (!_doSave)
            {
                canvas.ResetMatrix();
                //Draw circle overlay
                using (var frame = new SKPath())
                    using (var hole = new SKPath()) {
                        frame.AddRect(info.Rect);
                        hole.AddCircle(info.Width / 2, info.Height / 2, info.Width / 3);
                        SKPath frameHole = frame.Op(hole, SKPathOp.Difference);
                        using (var p = new SKPaint {
                            IsAntialias = true, Style = SKPaintStyle.Fill, Color = new SKColor(128, 128, 128, 200)
                        }) {
                            canvas.DrawPath(frameHole, p);
                        }
                    }
            }
            else
            {
                SKImage snapI = e.Surface.Snapshot();
                snapI = snapI.Subset(canvas.DeviceClipBounds);
                SKData pngImage = snapI.Encode();
                File.WriteAllBytes(_ballFilename, pngImage.ToArray());
                await Navigation.PopAsync();

                OnBallImageUpdated(_ballFilename);
            }
        }
コード例 #27
0
        public static byte[] CreateRoundImage(byte[] data, int size)
        {
            using (var bitmap = SKBitmap.Decode(data))
                using (var resultBitmap = new SKBitmap(size, size))
                    using (var canvas = new SKCanvas(resultBitmap))
                        using (var path = new SKPath())
                        {
                            var widthHeight = Math.Min(bitmap.Width, bitmap.Height);
                            var scale       = (float)size / widthHeight;

                            canvas.Clear();
                            path.AddCircle(size / 2, size / 2, size / 2);
                            canvas.ClipPath(path);
                            canvas.Scale(scale, scale);
                            canvas.DrawBitmap(bitmap, (widthHeight - bitmap.Width) / 2, (widthHeight - bitmap.Height) / 2);

                            return(ToPngData(resultBitmap));
                        }
        }
コード例 #28
0
        private void DrawInnerBlurRectangle(SKCanvas canvas, SKRect rect)
        {
            // create the rounded rectangle
            var roundedRect = new SKPath();

            roundedRect.AddRoundRect(rect, 10, 10);

            // draw the white background
            var p = new SKPaint
            {
                IsAntialias = true,
                Style       = SKPaintStyle.Fill,
                Color       = SKColors.White
            };

            canvas.DrawPath(roundedRect, p);

            using (new SKAutoCanvasRestore(canvas))
            {
                // clip the canvas to stop the blur from appearing outside
                canvas.ClipPath(roundedRect, SKClipOperation.Intersect, true);

                // draw the wide blur all around
                p.Color       = SKColors.Black;
                p.Style       = SKPaintStyle.Stroke;
                p.StrokeWidth = 2;
                p.MaskFilter  = SKMaskFilter.CreateBlur(SKBlurStyle.Normal, 2);
                canvas.Translate(0.5f, 1.5f);
                canvas.DrawPath(roundedRect, p);

                // draw the narrow blur at the top
                p.StrokeWidth = 1;
                p.MaskFilter  = SKMaskFilter.CreateBlur(SKBlurStyle.Normal, 1);
                canvas.DrawPath(roundedRect, p);
            }

            // draw the border
            p.StrokeWidth = 2;
            p.MaskFilter  = null;
            p.Color       = SampleMedia.Colors.XamarinGreen;
            canvas.DrawPath(roundedRect, p);
        }
コード例 #29
0
ファイル: SKSurfaceExtension.cs プロジェクト: Teeem/Captcha
        public static SKCanvas ClippingText(this SKCanvas canvas, SKImageInfo info, string text, SKPaint paint)
        {
            using (SKPath textPath = paint.GetTextPath(text, 0, 0))
            {
                // Set transform to center and enlarge clip path to window height
                SKRect bounds;
                textPath.GetTightBounds(out bounds);
                textPath.FillType = SKPathFillType.InverseWinding;
                canvas.Translate(info.Width / 2, info.Height / 2);
                canvas.Scale((info.Width / bounds.Width) * 0.9f, (info.Height / bounds.Height) * 0.9f);
                canvas.Translate(-bounds.MidX, -bounds.MidY);

                // Set the clip path
                canvas.ClipPath(textPath);
            }

            // Reset transforms
            canvas.ResetMatrix();
            return(canvas);
        }
コード例 #30
0
ファイル: CircularImage.cs プロジェクト: ycfft/TimelinePulse
        protected override void OnPaintSurface(SKPaintSurfaceEventArgs args)
        {
            base.OnPaintSurface(args);

            SKImageInfo info    = args.Info;
            SKSurface   surface = args.Surface;
            SKCanvas    canvas  = surface.Canvas;

            canvas.Clear();

            CircularPath.GetBounds(out SKRect bounds);
            canvas.Translate(info.Width / 2, info.Height / 2);
            canvas.Scale(0.98f * info.Height / bounds.Height);
            canvas.Translate(-bounds.MidX, -bounds.MidY);
            canvas.ClipPath(CircularPath);
            canvas.ResetMatrix();

            if (_resourceBitmap != null)
            {
                canvas.DrawBitmap(_resourceBitmap, info.Rect);
            }
        }