Пример #1
0
        /// <summary>
        /// Gets a <see cref="SKPaint"/> containing information needed to render a line.
        /// </summary>
        /// <remarks>
        /// This modifies and returns the local <see cref="paint"/> instance.
        /// </remarks>
        /// <param name="strokeColor">The stroke color.</param>
        /// <param name="strokeThickness">The stroke thickness.</param>
        /// <param name="edgeRenderingMode">The edge rendering mode.</param>
        /// <param name="dashArray">The dash array.</param>
        /// <param name="lineJoin">The line join.</param>
        /// <returns>The paint.</returns>
        private SKPaint GetLinePaint(OxyColor strokeColor, double strokeThickness, EdgeRenderingMode edgeRenderingMode, double[] dashArray, LineJoin lineJoin)
        {
            var paint = this.GetStrokePaint(strokeColor, strokeThickness, edgeRenderingMode);

            if (dashArray != null)
            {
                var actualDashArray = this.ConvertDashArray(dashArray, paint.StrokeWidth);
                paint.PathEffect = SKPathEffect.CreateDash(actualDashArray, 0);
            }

            paint.StrokeJoin = lineJoin switch
            {
                LineJoin.Miter => SKStrokeJoin.Miter,
                LineJoin.Round => SKStrokeJoin.Round,
                LineJoin.Bevel => SKStrokeJoin.Bevel,
                _ => throw new ArgumentOutOfRangeException(nameof(lineJoin))
            };

            return(paint);
        }
Пример #2
0
        /// <inheritdoc />
        public void DrawLine(Point point1, Point point2, IPaint paint)
        {
            using var skPaint = new SKPaint
                  {
                      Color       = paint.Fill.ToSkColor(paint.Opacity),
                      StrokeWidth = paint.StrokeThickness,
                      IsAntialias = paint.IsAntialiased,
                      IsStroke    = Math.Abs(paint.StrokeThickness) > float.Epsilon
                  };

            if (paint.DashPattern != null)
            {
                var dashEffect = SKPathEffect.CreateDash(paint.DashPattern, 0);
                skPaint.PathEffect = skPaint.PathEffect != null
                    ? SKPathEffect.CreateCompose(dashEffect, skPaint.PathEffect)
                    : dashEffect;
            }

            Surface.Canvas.DrawLine(point1.ToSkPoint(), point2.ToSkPoint(), skPaint);
        }
Пример #3
0
        public static SKPaint ToSKPaint(this Pen pen)
        {
            pen.nativePen.Style = SKPaintStyle.Stroke;
            return(pen.nativePen);

            var paint = new SKPaint
            {
                Color         = pen.Color.ToSKColor(),
                StrokeWidth   = pen.Width,
                IsAntialias   = true,
                Style         = SKPaintStyle.Stroke,
                BlendMode     = SKBlendMode.SrcOver,
                FilterQuality = SKFilterQuality.High
            };

            if (pen.DashStyle != DashStyle.Solid)
            {
                paint.PathEffect = SKPathEffect.CreateDash(pen.DashPattern, 0);
            }
            return(paint);
        }
        public static SKPaint MakeDefaultPaint(Color pColor, float pStrokeWidth, float pFontSize, SKTypeface pTypeface, bool Dotted = false, bool IsStroke = false)
        {
            var output = new SKPaint()
            {
                Color       = pColor.ToSKColor(),
                StrokeWidth = pStrokeWidth,
                Typeface    = pTypeface,
                TextSize    = pFontSize,
                StrokeCap   = SKStrokeCap.Round,
                BlendMode   = SKBlendMode.Src,
                IsStroke    = IsStroke,
                IsAntialias = true
            };

            if (Dotted)
            {
                output.ColorFilter = SKColorFilter.CreateBlendMode(pColor.ToSKColor(), SKBlendMode.Dst);
                output.PathEffect  = SKPathEffect.CreateDash(new[] { 1f, 1f }, 0);
            }
            return(output);
        }
Пример #5
0
        public LoopGraph()
        {
            InitializeComponent();

            DataContext = this;


            float[] dashArray = { 4, 4 };

            SKPathEffect dash = SKPathEffect.CreateDash(dashArray, 2);

            GridPaint1 = new SKPaint
            {
                Style       = SKPaintStyle.Stroke,
                Color       = SKColors.DarkGray,
                StrokeWidth = 1,
                StrokeCap   = SKStrokeCap.Round,
                PathEffect  = dash,
                IsAntialias = false
            };

            GraphPaint1 = new SKPaint
            {
                Style       = SKPaintStyle.Stroke,
                Color       = SKColors.LimeGreen,
                StrokeWidth = 3,
                StrokeCap   = SKStrokeCap.Round,
                IsAntialias = true
            };

            ErasePaint = new SKPaint
            {
                Style       = SKPaintStyle.Fill,
                Color       = SKColors.Black,
                IsAntialias = false
            };

            DataBufferYArray = new double[MaxBufferSize];
            DataBufferXArray = new double[MaxBufferSize];
        }
Пример #6
0
        // Initialize paints
        private void InitializePaints()
        {
            _selectionPaint = new SKPaint
            {
                Style       = SKPaintStyle.Stroke,
                Color       = Constants.SelectionStrokeColor,
                StrokeWidth = Constants.SelectionStrokeWidth,
                StrokeCap   = SKStrokeCap.Round,
                StrokeJoin  = SKStrokeJoin.Round,
                PathEffect  = SKPathEffect.CreateDash(new float[]
                {
                    Constants.SelectionPathDashLength, Constants.SelectionPathGapLength
                }, Constants.SelectionPathPhase)
            };

            _selectionPaintOutline = new SKPaint
            {
                Style       = SKPaintStyle.Stroke,
                Color       = Constants.SelectionStrokeOutlineColor,
                StrokeWidth = Constants.SelectionStrokeOutlineWidth,
                StrokeCap   = SKStrokeCap.Round,
                StrokeJoin  = SKStrokeJoin.Round,
                PathEffect  = SKPathEffect.CreateDash(new float[]
                {
                    Constants.SelectionPathDashLength, Constants.SelectionPathGapLength
                }, Constants.SelectionPathPhase)
            };

            _selectionPaintFill = new SKPaint
            {
                Style = SKPaintStyle.Fill,
                Color = Constants.SelectionFillColor
            };

            _completedSelectionFill = new SKPaint
            {
                Style = SKPaintStyle.Fill,
                Color = SKColors.White
            };
        }
Пример #7
0
        public LayoutRecord(HipsterEngine.Core.HipsterEngine engine)
        {
            _engine = engine;
            canvas  = _engine.Surface.Canvas;

            Radius     = _engine.Surface.Width / 5;
            Y          = _engine.Surface.Height - _engine.Surface.Height / 4;
            _x1Line1   = 0;
            _y1Line1   = Y;
            _x2Line1   = _engine.Surface.Width / 2 - Radius;
            _y2Line1   = Y;
            _x1Line2   = _engine.Surface.Width / 2 + Radius;
            _y1Line2   = Y;
            _x2Line2   = _engine.Surface.Width;
            _y2Line2   = Y;
            _circleX   = _engine.Surface.Width / 2;
            _circleY   = Y;
            _textX     = _engine.Surface.Width / 2 - 1;
            _textY     = Y + 16;
            TextRecord = "0";

            Paint = new SKPaint
            {
                Style       = SKPaintStyle.Stroke,
                StrokeWidth = 2,
                IsAntialias = true,
                PathEffect  = SKPathEffect.CreateDash(new[] { 10.0f, 10.0f }, 10),
                Color       = new SKColor(150, 150, 150)
            };

            PaintText = new SKPaint
            {
                IsAntialias = true,
                Color       = new SKColor(150, 150, 150),
                TextAlign   = SKTextAlign.Center,
                Typeface    = Assets.Typeface,
                TextSize    = 50
            };
        }
Пример #8
0
        void DrawChoice(SKCanvas canvas)
        {
            if (GameControls is null)
            {
                return;
            }
            if (GameControls.ViewModel.ChosenTurn != -1)
            {
                int     numDash    = 5;
                float   dashLength = 2 * (numDash - 1) + numDash;
                float[] dashArray  =
                {
                    ViewModel.CellSize / dashLength,
                    2 * ViewModel.CellSize / dashLength
                };
                SKPaint paint = new SKPaint
                {
                    Color       = SKColors.White,
                    Style       = SKPaintStyle.StrokeAndFill,
                    PathEffect  = SKPathEffect.CreateDash(dashArray, 20),
                    StrokeWidth = 8,
                    MaskFilter  = SKMaskFilter.CreateBlur(SKBlurStyle.Normal, 1)
                };
                SKPoint cur = ViewModel.GameTrajectory.Last();

                var(dir1, dir2) = GameControls.ViewModel.CurrentDirections;

                canvas.DrawLine(
                    ViewModel.GetGridPoint(cur),
                    ViewModel.GetGridPoint(ViewModel.MovePoint(cur, dir1)),
                    paint
                    );
                canvas.DrawLine(
                    ViewModel.GetGridPoint(cur),
                    ViewModel.GetGridPoint(ViewModel.MovePoint(cur, dir2)),
                    paint
                    );
            }
        }
        void OnCanvasViewPaintSurface(object sender, SKPaintSurfaceEventArgs args)
        {
            SKImageInfo info    = args.Info;
            SKSurface   surface = args.Surface;
            SKCanvas    canvas  = surface.Canvas;

            canvas.Clear();

            using (SKPaint strokePaint = new SKPaint
            {
                Style = SKPaintStyle.Stroke,
                Color = SKColors.Red,
                StrokeWidth = 3,
                PathEffect = SKPathEffect.CreateDash(new float[] { 7, 7 }, 0)
            })
                using (SKPaint textPaint = new SKPaint
                {
                    Style = SKPaintStyle.Fill,
                    Color = SKColors.Blue,
                    TextSize = 50
                })
                {
                    SKRect textBounds = new SKRect();
                    textPaint.MeasureText(Title, ref textBounds);
                    float margin = (info.Width - textBounds.Width) / 2;

                    float sx = (float)xScaleSlider.Value;
                    float sy = (float)yScaleSlider.Value;
                    float px = margin + textBounds.Width / 2;
                    float py = margin + textBounds.Height / 2;

                    canvas.Scale(sx, sy, px, py);

                    SKRect borderRect = SKRect.Create(new SKPoint(margin, margin), textBounds.Size);
                    canvas.DrawRoundRect(borderRect, 20, 20, strokePaint);
                    canvas.DrawText(Title, margin, -textBounds.Top + margin, textPaint);
                }
        }
Пример #10
0
        public static SKPathEffect ToSkia(this PenStyle penStyle, float width)
        {
            switch (penStyle)
            {
            case PenStyle.Dash:
                return(SKPathEffect.CreateDash(new [] { width * 4f, width * 3f }, 0));

            case PenStyle.Dot:
                return(SKPathEffect.CreateDash(new [] { width * 1f, width * 3f }, 0));

            case PenStyle.DashDot:
                return(SKPathEffect.CreateDash(new [] { width * 4f, width * 3f, width * 1f, width * 3f }, 0));

            case PenStyle.DashDotDot:
                return(SKPathEffect.CreateDash(new [] { width * 4f, width * 3f, width * 1f, width * 3f, width * 1f, width * 3f }, 0));

            case PenStyle.LongDash:
                return(SKPathEffect.CreateDash(new [] { width * 8f, width * 3f }, 0));

            case PenStyle.LongDashDot:
                return(SKPathEffect.CreateDash(new [] { width * 8f, width * 3f, width * 1f, width * 3f }, 0));

            case PenStyle.ShortDash:
                return(SKPathEffect.CreateDash(new [] { width * 2f, width * 3f }, 0));

            case PenStyle.ShortDashDot:
                return(SKPathEffect.CreateDash(new [] { width * 2f, width * 3f, width * 1f, width * 3f }, 0));

            case PenStyle.ShortDashDotDot:
                return(SKPathEffect.CreateDash(new [] { width * 2f, width * 3f, width * 1f, width * 3f, width * 1f, width * 3f }, 0));

            case PenStyle.ShortDot:
                return(SKPathEffect.CreateDash(new [] { width * 1f, width * 3f }, 0));

            default:
                return(SKPathEffect.CreateDash(new float[0], 0));
            }
        }
        static void DrawBox(SKCanvas canvas, float startLeft, float startTop, float scaledBoxWidth, float scaledBoxHeight, SKColor color)
        {
            var strokePaint = new SKPaint
            {
                IsAntialias = true,
                Style       = SKPaintStyle.Stroke,
                StrokeWidth = 5,
                PathEffect  = SKPathEffect.CreateDash(new[] { 20f, 20f }, 20f)
            };

            DrawBox(canvas, strokePaint, startLeft, startTop, scaledBoxWidth, scaledBoxHeight);

            var blurStrokePaint = new SKPaint
            {
                Style       = SKPaintStyle.Stroke,
                StrokeWidth = 5,
                PathEffect  = SKPathEffect.CreateDash(new[] { 20f, 20f }, 20f),
                IsAntialias = true,
                MaskFilter  = SKMaskFilter.CreateBlur(SKBlurStyle.Normal, 0.57735f * radius + 0.5f)
            };

            DrawBox(canvas, blurStrokePaint, startLeft, startTop, scaledBoxWidth, scaledBoxHeight);
        }
Пример #12
0
        public void DrawLineString(List <Point> geometry, Brush style)
        {
            if (ClipOverflow)
            {
                geometry = clipLine(geometry);
                if (geometry == null)
                {
                    return;
                }
            }

            var path = getPathFromGeometry(geometry);

            if (path == null)
            {
                return;
            }

            SKPaint fillPaint = new SKPaint
            {
                Style       = SKPaintStyle.Stroke,
                StrokeCap   = convertCap(style.Paint.LineCap),
                StrokeWidth = (float)style.Paint.LineWidth,
                Color       = new SKColor(style.Paint.LineColor.R, style.Paint.LineColor.G, style.Paint.LineColor.B, (byte)clamp(style.Paint.LineColor.A * style.Paint.LineOpacity, 0, 255)),
                IsAntialias = true,
            };

            if (style.Paint.LineDashArray.Count() > 0)
            {
                var effect = SKPathEffect.CreateDash(style.Paint.LineDashArray.Select(n => (float)n).ToArray(), 0);
                fillPaint.PathEffect = effect;
            }

            //Console.WriteLine(style.Paint.LineWidth);

            canvas.DrawPath(path, fillPaint);
        }
Пример #13
0
        void SKCanvasView_PaintSurface(object sender, SKPaintSurfaceEventArgs e)
        {
            SKImageInfo info    = e.Info;
            SKSurface   surface = e.Surface;
            SKCanvas    canvas  = surface.Canvas;

            canvas.Clear();

            var color = AppThemeConstants.LowPriorityColor;

            switch (Type)
            {
            case PriorityType.Low:
                color = AppThemeConstants.LowPriorityColor;
                break;

            case PriorityType.Medium:
                color = AppThemeConstants.MediumPriorityColor;
                break;

            case PriorityType.High:
                color = AppThemeConstants.HighPriorityColor;
                break;

            default:
                break;
            }
            canvas.DrawRoundRect(0, 0, info.Width, info.Height - 5, 15, 15, new SKPaint()
            {
                Style       = SKPaintStyle.Stroke,
                StrokeWidth = 3,
                StrokeCap   = SKStrokeCap.Round,
                StrokeJoin  = SKStrokeJoin.Round,
                Color       = color.ToSKColor(),
                PathEffect  = SKPathEffect.CreateDash(new float[] { 4, 4 }, 3f),
            });
        }
        public FastScrollingGraph()
        {
            InitializeComponent();

            DataContext = this;


            float[] dashArray = { 6, 6 };

            SKPathEffect dash = SKPathEffect.CreateDash(dashArray, 2);

            GridPaint1 = new SKPaint
            {
                Style       = SKPaintStyle.Stroke,
                Color       = SKColors.White,
                StrokeWidth = 4,
                StrokeCap   = SKStrokeCap.Round,
                PathEffect  = dash,
                IsAntialias = false
            };

            GraphPaint1 = new SKPaint
            {
                Style       = SKPaintStyle.Stroke,
                Color       = SKColors.LimeGreen,
                StrokeWidth = 3,
                StrokeCap   = SKStrokeCap.Round,
                IsAntialias = true
            };

            ErasePaint = new SKPaint
            {
                Style       = SKPaintStyle.Fill,
                Color       = SKColors.Black,
                IsAntialias = false
            };
        }
        public void Stroke(SKCanvas canvas, SKPath path, float size, StrokeStyle style, SKStrokeCap cap, SKStrokeJoin join)
        {
            using (var paint = new SKPaint()
            {
                IsAntialias = true,
                StrokeWidth = size,
                Color = this.Color,
                Style = SKPaintStyle.Stroke,
                StrokeCap = cap,
                StrokeJoin = join,
            })
            {
                if (style == StrokeStyle.Dotted)
                {
                    paint.PathEffect = SKPathEffect.CreateDash(new[] { 0, size * 2, 0, size * 2 }, 0);
                }
                else if (style == StrokeStyle.Dashed)
                {
                    paint.PathEffect = SKPathEffect.CreateDash(new[] { size * 6, size * 2 }, 0);
                }

                canvas.DrawPath(path, paint);
            }
        }
Пример #16
0
        public void DrawSnapLines(ModelViewSurface surface, SKCanvas canvas)
        {
            SKPaint dashPaint = new SKPaint()
            {
                Style      = SKPaintStyle.Stroke,
                Color      = Color.GreenYellow.ToSKColor(),
                PathEffect = SKPathEffect.CreateDash(new Single[2] {
                    surface.ViewHeight / 100, surface.ViewHeight / 100
                }, surface.ViewHeight / 80),
                IsAntialias = true,
                StrokeWidth = 1
            };

            if (SnapPoint.X != float.MinValue)
            {
                SKPoint pt = IssoConvert.IssoPoint2DToSkPoint(SnapPoint, surface.ScaleFactor, surface.Origin, surface.ViewHeight);
                canvas.DrawLine(pt.X, 0, pt.X, surface.ViewHeight, dashPaint);
            }
            if (SnapPoint.Y != float.MinValue)
            {
                SKPoint pt = IssoConvert.IssoPoint2DToSkPoint(SnapPoint, surface.ScaleFactor, surface.Origin, surface.ViewHeight);
                canvas.DrawLine(0, pt.Y, surface.ViewWidth, pt.Y, dashPaint);
            }
        }
Пример #17
0
        public override void OnLoad()
        {
            PaintWhite = new SKPaint
            {
                Style       = SKPaintStyle.Stroke,
                StrokeWidth = 2,
                IsAntialias = true,
                Color       = new SKColor(150, 150, 150)
            };
            PaintStroke = new SKPaint
            {
                Style       = SKPaintStyle.Stroke,
                IsAntialias = true,
                PathEffect  = SKPathEffect.CreateDash(new[] { 10.0f, 10.0f }, 10),
                Color       = new SKColor(210, 170, 0, 100)
            };
            Number = 3;

            Paint  += OnPaint;
            Update += OnUpdate;

            TimerForIntent            = new TimeWatch();
            TimerForIntent.Tick      += tick => { Alpha = (byte)tick; };
            TimerForIntent.Complated += tick => HipsterEngine.Screens.SetScreen(new NavigatorScreen());

            Timer       = new TimeWatch();
            Timer.Tick += tick =>
            {
                Number = 3 - tick;
            };
            Timer.Complated += tick =>
            {
                TimerForIntent.Start(0, 255);
            };
            Timer.Start(100, 3);
        }
Пример #18
0
        public override void Draw(Diagram diagram)
        {
            SKPaint paint = new SKPaint
            {
                Color       = Colour,
                IsAntialias = true,
                StrokeWidth = Thickness,
                StrokeCap   = SKStrokeCap.Round,
                Style       = SKPaintStyle.Stroke
            };

            if (StyleOfLine == LineStyle.Dashed)
            {
                paint.PathEffect = SKPathEffect.CreateDash(new float[] { 9f, 3f }, 0);
            }

            SKPath path = new SKPath();

            if (TypeOfLine == LineType.Line)
            {
                path.MoveTo(X1, Y1);
                path.LineTo(X2, Y2);
                diagram.DiagramSurface.Canvas.DrawPath(path, paint);
            }
            else if (TypeOfLine == LineType.Sharp)
            {
                path.MoveTo(X1, Y1);

                foreach (float[] coordPair in ControlPoints)
                {
                    path.LineTo(coordPair[0], coordPair[1]);
                }

                path.LineTo(X2, Y2);
                diagram.DiagramSurface.Canvas.DrawPath(path, paint);
            }
            else if (TypeOfLine == LineType.Curve)
            {
                List <float[]> cpts = new List <float[]>();

                path.MoveTo(X1, Y1);
                path.CubicTo(ControlPoints[0][0], ControlPoints[0][1], ControlPoints[1][0], ControlPoints[1][1], X2, Y2);
                diagram.DiagramSurface.Canvas.DrawPath(path, paint);
            }
            else
            {
                Log.LogMessageError("An invalid line type has somehow been assigned: " + TypeOfLine);
            }

            if (HeadType == EndType.Arrow || TailType == EndType.Arrow || HeadType == EndType.Half_Arrow || TailType == EndType.Half_Arrow)
            {
                double tailAngle = Math.Atan2(Y1 - Y2, X1 - X2);
                if (TypeOfLine != LineType.Line)
                {
                    tailAngle = Math.Atan2(ControlPoints[ControlPoints.Count - 1][1] - Y2, ControlPoints[ControlPoints.Count - 1][0] - X2);
                }

                double headAngle = Math.Atan2(Y2 - Y1, X2 - X1);
                if (TypeOfLine != LineType.Line)
                {
                    try
                    {
                        headAngle = Math.Atan2(ControlPoints[0][1] - Y1, ControlPoints[0][0] - X1);
                    }
                    catch
                    {
                        // Nothing.
                    }
                }

                if (HeadType == EndType.Arrow || HeadType == EndType.Half_Arrow)
                {
                    SKPath p2 = new SKPath(), p3 = new SKPath();

                    double ha1, ha2;
                    ha1 = headAngle + ArrowOffset;
                    ha2 = headAngle - ArrowOffset;

                    float dPointX1 = X1 + (float)(16 * Math.Cos(ha1));
                    float dPointY1 = Y1 + (float)(16 * Math.Sin(ha1));

                    float dPointX2 = X1 + (float)(16 * Math.Cos(ha2));
                    float dPointY2 = Y1 + (float)(16 * Math.Sin(ha2));

                    p2.MoveTo(X1, Y1);
                    p2.LineTo(dPointX1, dPointY1);

                    p3.MoveTo(X1, Y1);
                    p3.LineTo(dPointX2, dPointY2);

                    diagram.DiagramSurface.Canvas.DrawPath(p2, paint);
                    if (HeadType == EndType.Arrow)
                    {
                        diagram.DiagramSurface.Canvas.DrawPath(p3, paint);
                    }
                }

                if (TailType == EndType.Arrow || TailType == EndType.Half_Arrow)
                {
                    SKPath p2 = new SKPath(), p3 = new SKPath();

                    double ta1, ta2;
                    ta1 = tailAngle + ArrowOffset;
                    ta2 = tailAngle - ArrowOffset;

                    float dPointX1 = X2 + (float)(16 * Math.Cos(ta1));
                    float dPointY1 = Y2 + (float)(16 * Math.Sin(ta1));

                    float dPointX2 = X2 + (float)(16 * Math.Cos(ta2));
                    float dPointY2 = Y2 + (float)(16 * Math.Sin(ta2));

                    p2.MoveTo(X2, Y2);
                    p2.LineTo(dPointX1, dPointY1);

                    p3.MoveTo(X2, Y2);
                    p3.LineTo(dPointX2, dPointY2);

                    diagram.DiagramSurface.Canvas.DrawPath(p2, paint);
                    if (TailType == EndType.Arrow)
                    {
                        diagram.DiagramSurface.Canvas.DrawPath(p3, paint);
                    }
                }
            }
            paint.Dispose();
        }
Пример #19
0
        public override void DrawContent(SKCanvas canvas, int width, int height)
        {
            var total = Series.Count();

            if (total > 0)
            {
                var captionHeight = Series.First().Max(x =>
                {
                    var result = 0.0f;

                    var hasLabel      = !string.IsNullOrEmpty(x.Label);
                    var hasValueLabel = !string.IsNullOrEmpty(x.ValueLabel);
                    if (hasLabel || hasValueLabel)
                    {
                        var hasOffset     = hasLabel && hasValueLabel;
                        var captionMargin = LabelTextSize * 0.60f;
                        var space         = hasOffset ? captionMargin : 0;

                        if (hasLabel)
                        {
                            result += LabelTextSize;
                        }

                        if (hasValueLabel)
                        {
                            result += LabelTextSize;
                        }
                    }

                    return(result);
                });

                var center     = new SKPoint(width / 2, height / 2);
                var radius     = ((Math.Min(width, height) - (2 * Margin)) / 2) - captionHeight;
                var rangeAngle = (float)((Math.PI * 2) / total);
                var startAngle = (float)Math.PI;

                var nextEntry = Series.First().First();
                var nextAngle = startAngle;
                var nextPoint = GetPoint(nextEntry.Value, center, nextAngle, radius);

                DrawBorder(canvas, center, radius);

                for (int i = 0; i < total; i++)
                {
                    var angle = nextAngle;
                    var entry = nextEntry;
                    var point = nextPoint;

                    var nextIndex = (i + 1) % total;
                    nextAngle = startAngle + (rangeAngle * nextIndex);
                    nextEntry = Series.First().ElementAt(nextIndex);
                    nextPoint = GetPoint(nextEntry.Value, center, nextAngle, radius);

                    // Border center bars
                    using (var paint = new SKPaint()
                    {
                        Style = SKPaintStyle.Stroke,
                        StrokeWidth = BorderLineSize,
                        Color = BorderLineColor,
                        IsAntialias = true,
                    })
                    {
                        var borderPoint = GetPoint(MaxValue, center, angle, radius);
                        canvas.DrawLine(point.X, point.Y, borderPoint.X, borderPoint.Y, paint);
                    }

                    // Values points and lines
                    using (var paint = new SKPaint()
                    {
                        Style = SKPaintStyle.Stroke,
                        StrokeWidth = BorderLineSize,
                        Color = entry.Color.WithAlpha((byte)(entry.Color.Alpha * 0.75f)),
                        PathEffect = SKPathEffect.CreateDash(new[] { BorderLineSize, BorderLineSize * 2 }, 0),
                        IsAntialias = true,
                    })
                    {
                        var amount = Math.Abs(entry.Value - AbsoluteMinimum) / ValueRange;
                        canvas.DrawCircle(center.X, center.Y, radius * amount, paint);
                    }

                    canvas.DrawGradientLine(center, entry.Color.WithAlpha(0), point,
                                            entry.Color.WithAlpha((byte)(entry.Color.Alpha * 0.75f)), LineSize);
                    canvas.DrawGradientLine(point, entry.Color, nextPoint, nextEntry.Color, LineSize);
                    canvas.DrawPoint(point, entry.Color, PointSize, PointMode);

                    // Labels
                    var labelPoint = GetPoint(MaxValue, center, angle, radius + LabelTextSize + (PointSize / 2));
                    var alignment  = SKTextAlign.Left;

                    if ((Math.Abs(angle - (startAngle + Math.PI)) < Epsilon) || (Math.Abs(angle - Math.PI) < Epsilon))
                    {
                        alignment = SKTextAlign.Center;
                    }
                    else if (angle > (float)(startAngle + Math.PI))
                    {
                        alignment = SKTextAlign.Right;
                    }

                    canvas.DrawCaptionLabels(entry.Label, entry.TextColor, entry.ValueLabel, entry.Color, LabelTextSize,
                                             labelPoint, alignment);
                }
            }
        }
Пример #20
0
        private void DrawDominoBorder(SKCanvas canvas, EditingDominoVM vm)
        {
            var shape = vm.domino;
            var c     = vm.StoneColor;
            var dp    = vm.CanvasPoints;
            // is the domino visible at all?
            // todo: speed up this call
            var inside = dp.Select(x => new Avalonia.Point(x.X, x.Y)).Sum(x => Bounds.Contains(PointToDisplayAvaloniaPoint(x)) ? 1 : 0);

            if (inside > 0)
            {
                var path = new SKPath();
                path.MoveTo(PointToDisplaySkiaPoint(dp[0]));
                foreach (var line in dp.Skip(0))
                {
                    path.LineTo(PointToDisplaySkiaPoint(line));
                }
                path.Close();
                SKColor?borderColor = null;
                if (vm.State.HasFlag(EditingDominoStates.PasteHighlight))
                {
                    borderColor = pasteHightlightColor;
                }
                if (vm.State.HasFlag(EditingDominoStates.Selected))
                {
                    borderColor = selectedBorderColor;
                }
                if (vm.State.HasFlag(EditingDominoStates.DeletionHighlight))
                {
                    borderColor = deletionHighlightColor;
                }

                if (borderColor != null)
                {
                    canvas.DrawPath(path, new SKPaint()
                    {
                        Color = (SKColor)borderColor, IsAntialias = true, IsStroke = true, StrokeWidth = Math.Max(BorderSize, 2) * zoom, PathEffect = SKPathEffect.CreateDash(new float[] { 8 * zoom, 2 * zoom }, 10 * zoom)
                    });
                }
                else
                {
                    if (BorderSize > 0)
                    {
                        canvas.DrawPath(path, new SKPaint()
                        {
                            Color = unselectedBorderColor, IsAntialias = true, IsStroke = true, StrokeWidth = BorderSize / 2 * zoom
                        });
                    }
                }
            }
        }
Пример #21
0
        public SKPaint CreatePaint(EvaluationContext context)
        {
            if (context.Equals(lastContext))
            {
                return(lastPaint);
            }

            if (variableColor || variableOpacity)
            {
                var c = variableColor ? funcColor(context) : color;
                var o = variableOpacity ? funcOpacity(context) : opacity;
                paint.Color = c.WithAlpha((byte)(c.Alpha * o));
            }

            if (variableStyle)
            {
                paint.Style = funcStyle(context);
            }

            if (variableAntialias)
            {
                paint.IsAntialias = funcAntialias(context);
            }

            if (variableStrokeWidth)
            {
                paint.StrokeWidth = funcStrokeWidth(context) * context.Scale;
            }
            else
            {
                paint.StrokeWidth = strokeWidth * context.Scale;
            }

            if (variableStrokeCap)
            {
                paint.StrokeCap = funcStrokeCap(context);
            }

            if (variableStrokeJoin)
            {
                paint.StrokeJoin = funcStrokeJoin(context);
            }

            if (variableStrokeMiter)
            {
                paint.StrokeMiter = funcStrokeMiter(context);
            }

            if (variableShader)
            {
                paint.Shader = funcShader(context);
            }

            // We have to multiply the dasharray with the linewidth
            if (variableDashArray)
            {
                var array = funcDashArray(context);
                for (var i = 0; i < array.Length; i++)
                {
                    array[i] = array[i] * paint.StrokeWidth;
                }
                paint.PathEffect = SKPathEffect.CreateDash(array, 0);
            }
            else if (fixDashArray != null)
            {
                var array = new float[fixDashArray.Length];
                for (var i = 0; i < array.Length; i++)
                {
                    array[i] = fixDashArray[i] * paint.StrokeWidth;
                }
                paint.PathEffect = SKPathEffect.CreateDash(array, 0);
            }

            lastContext = new EvaluationContext(context.Zoom, context.Scale, context.Tags);
            lastPaint   = paint;

            return(paint);
        }
        public TrendGraph()
        {
            InitializeComponent();

            DataContext = this;


            float[] dashArray = { 6, 6 };

            SKPathEffect dash = SKPathEffect.CreateDash(dashArray, 2);

            GridPaint1 = new SKPaint
            {
                Style       = SKPaintStyle.Stroke,
                Color       = SKColors.Black,
                StrokeWidth = 2,
                StrokeCap   = SKStrokeCap.Round,
                PathEffect  = dash,
                TextSize    = 20f,
                IsAntialias = true
            };

            GridText1 = new SKPaint
            {
                Color       = SKColors.Black,
                StrokeWidth = 2,
                TextSize    = 20f,
                IsAntialias = true
            };

            GraphPaint1 = new SKPaint
            {
                Style = SKPaintStyle.StrokeAndFill,

                Color       = SKColors.DarkGreen,
                StrokeWidth = 1,
                TextSize    = 20,
                Typeface    = SKTypeface.FromFamilyName("Arial", SKFontStyleWeight.Normal, SKFontStyleWidth.Normal, SKFontStyleSlant.Upright),
                StrokeCap   = SKStrokeCap.Round,
                IsAntialias = true
            };

            GraphPaint2 = new SKPaint
            {
                Style       = SKPaintStyle.StrokeAndFill,
                Color       = SKColors.Fuchsia,
                StrokeWidth = 1,
                TextSize    = 20,
                Typeface    = SKTypeface.FromFamilyName("Arial", SKFontStyleWeight.Normal, SKFontStyleWidth.Normal, SKFontStyleSlant.Upright),

                StrokeCap   = SKStrokeCap.Round,
                IsAntialias = true
            };

            GraphPaint3 = new SKPaint
            {
                Style       = SKPaintStyle.StrokeAndFill,
                Color       = SKColors.Black,
                StrokeWidth = 1,
                TextSize    = 20,
                Typeface    = SKTypeface.FromFamilyName("Arial", SKFontStyleWeight.Normal, SKFontStyleWidth.Normal, SKFontStyleSlant.Upright),

                StrokeCap   = SKStrokeCap.Round,
                IsAntialias = true
            };

            GraphPaint4 = new SKPaint
            {
                Style       = SKPaintStyle.StrokeAndFill,
                Color       = SKColors.Red,
                StrokeWidth = 1,
                TextSize    = 20,
                Typeface    = SKTypeface.FromFamilyName("Arial", SKFontStyleWeight.Normal, SKFontStyleWidth.Normal, SKFontStyleSlant.Upright),

                StrokeCap   = SKStrokeCap.Round,
                IsAntialias = true
            };

            GraphPaint5 = new SKPaint
            {
                Style       = SKPaintStyle.Stroke,
                Color       = SKColors.Red,
                StrokeWidth = 1,
                TextSize    = 20,
                Typeface    = SKTypeface.FromFamilyName("Arial", SKFontStyleWeight.Normal, SKFontStyleWidth.Normal, SKFontStyleSlant.Upright),

                StrokeCap   = SKStrokeCap.Round,
                IsAntialias = true
            };


            ErasePaint = new SKPaint
            {
                Style       = SKPaintStyle.Fill,
                Color       = SKColors.White,
                IsAntialias = false
            };
        }
Пример #23
0
        public override void DrawContent(SKCanvas canvas, int width, int height)
        {
            var total = this.Entries?.Count() ?? 0;

            if (total > 0)
            {
                var captionHeight = this.Entries.Max(x =>
                {
                    var result = 0.0f;

                    var hasLabel      = !string.IsNullOrEmpty(x.Label);
                    var hasValueLabel = !string.IsNullOrEmpty(x.ValueLabel);
                    if (hasLabel || hasValueLabel)
                    {
                        var hasOffset     = hasLabel && hasValueLabel;
                        var captionMargin = this.LabelTextSize * 0.60f;
                        var space         = hasOffset ? captionMargin : 0;

                        if (hasLabel)
                        {
                            result += this.LabelTextSize;
                        }

                        if (hasValueLabel)
                        {
                            result += this.LabelTextSize;
                        }
                    }

                    return(result);
                });

                var center     = new SKPoint(width / 2, height / 2);
                var radius     = ((Math.Min(width, height) - (2 * Margin)) / 2) - captionHeight;
                var rangeAngle = (float)((Math.PI * 2) / total);
                var startAngle = (float)Math.PI;

                var nextEntry = this.Entries.First();
                var nextAngle = startAngle;
                var nextPoint = this.GetPoint(nextEntry.Value * this.AnimationProgress, center, nextAngle, radius);

                this.DrawBorder(canvas, center, radius);

                using (var clip = new SKPath())
                {
                    clip.AddCircle(center.X, center.Y, radius);

                    for (int i = 0; i < total; i++)
                    {
                        var angle = nextAngle;
                        var entry = nextEntry;
                        var point = nextPoint;

                        var nextIndex = (i + 1) % total;
                        nextAngle = startAngle + (rangeAngle * nextIndex);
                        nextEntry = this.Entries.ElementAt(nextIndex);
                        nextPoint = this.GetPoint(nextEntry.Value * this.AnimationProgress, center, nextAngle, radius);

                        canvas.Save();
                        canvas.ClipPath(clip);

                        // Border center bars
                        using (var paint = new SKPaint()
                        {
                            Style = SKPaintStyle.Stroke,
                            StrokeWidth = this.BorderLineSize,
                            Color = this.BorderLineColor,
                            IsAntialias = true,
                        })
                        {
                            var borderPoint = this.GetPoint(this.MaxValue, center, angle, radius);
                            canvas.DrawLine(point.X, point.Y, borderPoint.X, borderPoint.Y, paint);
                        }

                        // Values points and lines
                        using (var paint = new SKPaint()
                        {
                            Style = SKPaintStyle.Stroke,
                            StrokeWidth = this.BorderLineSize,
                            Color = entry.Color.WithAlpha((byte)(entry.Color.Alpha * 0.75f * this.AnimationProgress)),
                            PathEffect = SKPathEffect.CreateDash(new[] { this.BorderLineSize, this.BorderLineSize * 2 }, 0),
                            IsAntialias = true,
                        })
                        {
                            var amount = Math.Abs(entry.Value - this.AbsoluteMinimum) / this.ValueRange;
                            canvas.DrawCircle(center.X, center.Y, radius * amount, paint);
                        }

                        canvas.DrawGradientLine(center, entry.Color.WithAlpha(0), point, entry.Color.WithAlpha((byte)(entry.Color.Alpha * 0.75f)), this.LineSize);
                        canvas.DrawGradientLine(point, entry.Color, nextPoint, nextEntry.Color, this.LineSize);
                        canvas.DrawPoint(point, entry.Color, this.PointSize, this.PointMode);

                        canvas.Restore();

                        // Labels
                        var labelPoint = new SKPoint(0, radius + this.LabelTextSize + (this.PointSize / 2));
                        var rotation   = SKMatrix.MakeRotation(angle);
                        labelPoint = center + rotation.MapPoint(labelPoint);
                        var alignment = SKTextAlign.Left;

                        if ((Math.Abs(angle - (startAngle + Math.PI)) < Epsilon) || (Math.Abs(angle - Math.PI) < Epsilon))
                        {
                            alignment = SKTextAlign.Center;
                        }
                        else if (angle > (float)(startAngle + Math.PI))
                        {
                            alignment = SKTextAlign.Right;
                        }

                        canvas.DrawCaptionLabels(entry.Label, entry.TextColor, entry.ValueLabel, entry.Color.WithAlpha((byte)(255 * this.AnimationProgress)), this.LabelTextSize, labelPoint, alignment, base.Typeface, out var _);
                    }
                }
            }
        }
Пример #24
0
        protected override void OnPaintSurface(SKPaintSurfaceEventArgs e)
        {
            base.OnPaintSurface(e);

            SKRect    skRect  = new SKRect(e.Info.Rect.Left, e.Info.Rect.Top, e.Info.Rect.Right, e.Info.Rect.Bottom);
            SKSurface surface = e.Surface;
            SKCanvas  canvas  = surface.Canvas;

            canvas.Clear(myBackgroundColor);

            SKPaint paint = new SKPaint
            {
                Style       = SKPaintStyle.Fill,
                TextSize    = 28,
                StrokeWidth = ChartWidth,
                IsAntialias = true
            };

            SKPaint paintAxis = new SKPaint
            {
                Style       = SKPaintStyle.Fill,
                TextSize    = 14,
                StrokeWidth = LineWidth,
                IsAntialias = true,
                Color       = myColorText
            };

            SKPaint paintLinesAxis = new SKPaint
            {
                Style       = SKPaintStyle.Fill,
                TextSize    = 14,
                StrokeWidth = LineWidth,
                IsAntialias = true,
                Color       = myColorAxis,
                StrokeCap   = SKStrokeCap.Round,
                PathEffect  = SKPathEffect.CreateDash(new[] { 2f, 6f }, 0)
            };

            //paint.Style = SKPaintStyle.Stroke;
            paint.Color = myColorAxis;

            // title
            //SKPoint ptTitle=new SKPoint(leftMargin,topMargin);
            //canvas.DrawText(myTitle, ptTitle, paint);
            using (var paintTitle = new SKPaint())
            {
                paintTitle.TextSize    = 24.0f;
                paintTitle.IsAntialias = true;
                paintTitle.Color       = myColorTitle;
                paintTitle.IsStroke    = true;
                paintTitle.StrokeWidth = 1;
                paintTitle.TextAlign   = SKTextAlign.Center;

                canvas.DrawText(myTitle, e.Info.Width / 2f, topMargin, paintTitle);
            }
            //Y Axis
            SKPoint ptAxis = new SKPoint(leftMargin + 2, topMargin);

            canvas.DrawText(myTitleY, ptAxis, paintAxis);

            // Y Axis
            ptAxis = new SKPoint(skRect.Right - rightMargin, skRect.Bottom - bottomMargin);
            canvas.DrawText(myTitleX, ptAxis, paintAxis);
            // draw axis
            SKPoint pt1 = new SKPoint(skRect.Left + leftMargin, skRect.Bottom - bottomMargin);
            SKPoint pt2 = new SKPoint(skRect.Right - rightMargin, skRect.Bottom - bottomMargin);

            canvas.DrawLine(pt1, pt2, paintAxis);

            pt1 = new SKPoint(skRect.Left + leftMargin, skRect.Bottom - bottomMargin);
            pt2 = new SKPoint(skRect.Left + leftMargin, skRect.Top - topMargin);
            canvas.DrawLine(pt1, pt2, paintAxis);

            List <SKPoint> pointList = new List <SKPoint>();

            if (timeSeries.Count > 0)
            {
                float onex = (skRect.Width - leftMargin - rightMargin) / timeSeries.Count;
                float oney = (skRect.Height - topMargin - bottomMargin) / timeSeries.Max;

                for (float st = 0; st < this.timeSeries.Max; st += stepY)
                {
                    ptAxis = new SKPoint(skRect.Left + leftMargin + 4, skRect.Bottom - bottomMargin - st * oney);
                    if (st > 0)
                    {
                        SKPoint ptLine = new SKPoint(skRect.Right - rightMargin, skRect.Bottom - bottomMargin - st * oney);
                        canvas.DrawLine(ptAxis, ptLine, paintLinesAxis);
                    }
                    canvas.DrawText(st.ToString("0"), ptAxis, paintAxis);
                }

                int index = 0;
                foreach (TimeValue val in timeSeries)
                {
                    float   x  = index * onex;
                    float   y  = oney * val.Value;
                    SKPoint pt = new SKPoint(leftMargin + x, skRect.Bottom - bottomMargin - y);
                    pointList.Add(pt);
                    index++;
                }

                SKPoint[] points = pointList.ToArray();
                paint.Style = SKPaintStyle.Stroke;
                paint.Color = myColorLine;
                if (pointList.Count > 0)
                {
                    SKPoint origin = new SKPoint(skRect.Left + leftMargin, skRect.Bottom - bottomMargin);
                    var     path   = new SKPath();

                    path.MoveTo(points.First().X, origin.Y);
                    path.LineTo(points.First());

                    var       last      = points.Length;
                    TimeValue lastMonth = null;
                    for (int i = 0; i < last; i++)
                    {
                        SKPoint   pt   = points[i];
                        TimeValue tval = timeSeries[i];
                        if (lastMonth == null || tval.DateTime.Month != lastMonth.DateTime.Month)
                        {
                            lastMonth = tval;
                            ptAxis    = new SKPoint(pt.X, skRect.Bottom - (bottomMargin / 2));
                            canvas.DrawText(lastMonth.DateTime.ToString("MM/yy"), ptAxis, paintAxis);
                        }
                        if (i == 0)
                        {
                            path.LineTo(pt);
                        }
                        else
                        {
                            SKPoint pt0 = points[i - 1];
                            path.ConicTo(pt0, pt, Math.Abs(pt.X - pt0.X));
                        }
                    }

                    canvas.DrawPath(path, paint);
                }
            }
        }
Пример #25
0
 /// <summary>
 /// Creates the path effect.
 /// </summary>
 /// <param name="drawingContext">The drawing context.</param>
 public override void CreateEffect(SkiaSharpDrawingContext drawingContext)
 {
     SKPathEffect = SKPathEffect.CreateDash(_dashArray, _phase);
 }
Пример #26
0
        /// <summary>
        /// Creates paint wrapper for given pen.
        /// </summary>
        /// <param name="pen">Source pen.</param>
        /// <param name="targetSize">Target size.</param>
        /// <returns></returns>
        private PaintWrapper CreatePaint(Pen pen, Size targetSize)
        {
            var rv    = CreatePaint(pen.Brush, targetSize);
            var paint = rv.Paint;

            paint.IsStroke    = true;
            paint.StrokeWidth = (float)pen.Thickness;

            // Need to modify dashes due to Skia modifying their lengths
            // https://docs.microsoft.com/en-us/xamarin/xamarin-forms/user-interface/graphics/skiasharp/paths/dots
            // TODO: Still something is off, dashes are now present, but don't look the same as D2D ones.
            float dashLengthModifier;
            float gapLengthModifier;

            switch (pen.StartLineCap)
            {
            case PenLineCap.Round:
                paint.StrokeCap    = SKStrokeCap.Round;
                dashLengthModifier = -paint.StrokeWidth;
                gapLengthModifier  = paint.StrokeWidth;
                break;

            case PenLineCap.Square:
                paint.StrokeCap    = SKStrokeCap.Square;
                dashLengthModifier = -paint.StrokeWidth;
                gapLengthModifier  = paint.StrokeWidth;
                break;

            default:
                paint.StrokeCap    = SKStrokeCap.Butt;
                dashLengthModifier = 0.0f;
                gapLengthModifier  = 0.0f;
                break;
            }

            switch (pen.LineJoin)
            {
            case PenLineJoin.Miter:
                paint.StrokeJoin = SKStrokeJoin.Miter;
                break;

            case PenLineJoin.Round:
                paint.StrokeJoin = SKStrokeJoin.Round;
                break;

            default:
                paint.StrokeJoin = SKStrokeJoin.Bevel;
                break;
            }

            paint.StrokeMiter = (float)pen.MiterLimit;

            if (pen.DashStyle?.Dashes != null && pen.DashStyle.Dashes.Count > 0)
            {
                var srcDashes   = pen.DashStyle.Dashes;
                var dashesArray = new float[srcDashes.Count];

                for (var i = 0; i < srcDashes.Count; ++i)
                {
                    var lengthModifier = i % 2 == 0 ? dashLengthModifier : gapLengthModifier;

                    // Avalonia dash lengths are relative, but Skia takes absolute sizes - need to scale
                    dashesArray[i] = (float)srcDashes[i] * paint.StrokeWidth + lengthModifier;
                }

                var pe = SKPathEffect.CreateDash(dashesArray, (float)pen.DashStyle.Offset);

                paint.PathEffect = pe;
                rv.AddDisposable(pe);
            }

            return(rv);
        }
Пример #27
0
        private void DrawBackground(SKCanvas canvas, SKRect frame)
        {
            if (!HasBackground)
            {
                return;
            }

            using (var paint = new SKPaint
            {
                IsAntialias = true,
                Color = ChartBackgroundColor.ToSKColor(),
                Style = LineBackground ? SKPaintStyle.Stroke : SKPaintStyle.Fill,
                IsStroke = LineBackground,
            })
            {
                if (DashedFrame)
                {
                    paint.PathEffect = SKPathEffect.CreateDash(new float[] { 12, 12 }, 0);
                }

                if (LineBackground)
                {
                    paint.StrokeWidth = 2f;
                }

                var items = ChartValueItemsXPoints;

                var width = frame.GetItemWidth(MaxItems);

                for (int i = 0; i < items.Count; i++)
                {
                    if (LineBackground)
                    {
                        var item = items[i];

                        var left = item.Item2;

                        if (i != 0 && i != items.Count - 1)
                        {
                            canvas.DrawLine(left, frame.Bottom, left, frame.Top, paint);
                        }
                    }
                    else
                    {
                        if (i % 2 != 0)
                        {
                            continue;
                        }

                        var item = items[i];

                        var left = item.Item2;

                        // Don't draw outside frame
                        if ((left + (width * 2)).ToRounded() <= (frame.Right + FrameWidth).ToRounded())
                        {
                            canvas.DrawRect(left + width, frame.Top, width, frame.Height - FrameWidth, paint);
                        }
                    }
                }
            }
        }
Пример #28
0
        private void ReadPaints(Dictionary <string, string> style, ref SKPaint strokePaint, ref SKPaint fillPaint, bool isGroup)
        {
            // get current element opacity, but ignore for groups (special case)
            float elementOpacity = isGroup ? 1.0f : ReadOpacity(style);

            // stroke
            var stroke = GetString(style, "stroke").Trim();

            if (stroke.Equals("none", StringComparison.OrdinalIgnoreCase))
            {
                strokePaint = null;
            }
            else
            {
                if (string.IsNullOrEmpty(stroke))
                {
                    // no change
                }
                else
                {
                    if (strokePaint == null)
                    {
                        strokePaint = CreatePaint(true);
                    }

                    SKColor color;
                    if (ColorHelper.TryParse(stroke, out color))
                    {
                        // preserve alpha
                        if (color.Alpha == 255)
                        {
                            strokePaint.Color = color.WithAlpha(strokePaint.Color.Alpha);
                        }
                        else
                        {
                            strokePaint.Color = color;
                        }
                    }
                }

                // stroke attributes
                var strokeDashArray = GetString(style, "stroke-dasharray");
                if (!string.IsNullOrWhiteSpace(strokeDashArray))
                {
                    if ("none".Equals(strokeDashArray, StringComparison.OrdinalIgnoreCase))
                    {
                        // remove any dash
                        if (strokePaint != null)
                        {
                            strokePaint.PathEffect = null;
                        }
                    }
                    else
                    {
                        if (strokePaint == null)
                        {
                            strokePaint = CreatePaint(true);
                        }

                        // get the dash
                        var dashesStrings = strokeDashArray.Split(new[] { ' ', ',' }, StringSplitOptions.RemoveEmptyEntries);
                        var dashes        = dashesStrings.Select(ReadNumber).ToArray();
                        if (dashesStrings.Length % 2 == 1)
                        {
                            dashes = dashes.Concat(dashes).ToArray();
                        }
                        // get the offset
                        var strokeDashOffset = ReadNumber(style, "stroke-dashoffset", 0);
                        // set the effect
                        strokePaint.PathEffect = SKPathEffect.CreateDash(dashes.ToArray(), strokeDashOffset);
                    }
                }

                var strokeWidth = GetString(style, "stroke-width");
                if (!string.IsNullOrWhiteSpace(strokeWidth))
                {
                    if (strokePaint == null)
                    {
                        strokePaint = CreatePaint(true);
                    }
                    strokePaint.StrokeWidth = ReadNumber(strokeWidth);
                }

                var strokeOpacity = GetString(style, "stroke-opacity");
                if (!string.IsNullOrWhiteSpace(strokeOpacity))
                {
                    if (strokePaint == null)
                    {
                        strokePaint = CreatePaint(true);
                    }
                    strokePaint.Color = strokePaint.Color.WithAlpha((byte)(ReadNumber(strokeOpacity) * 255));
                }

                if (strokePaint != null)
                {
                    strokePaint.Color = strokePaint.Color.WithAlpha((byte)(strokePaint.Color.Alpha * elementOpacity));
                }
            }

            // fill
            var fill = GetString(style, "fill").Trim();

            if (fill.Equals("none", StringComparison.OrdinalIgnoreCase))
            {
                fillPaint = null;
            }
            else
            {
                if (string.IsNullOrEmpty(fill))
                {
                    // no change
                }
                else
                {
                    if (fillPaint == null)
                    {
                        fillPaint = CreatePaint();
                    }

                    SKColor color;
                    if (ColorHelper.TryParse(fill, out color))
                    {
                        // preserve alpha
                        if (color.Alpha == 255)
                        {
                            fillPaint.Color = color.WithAlpha(fillPaint.Color.Alpha);
                        }
                        else
                        {
                            fillPaint.Color = color;
                        }
                    }
                    else
                    {
                        var read = false;
                        var urlM = fillUrlRe.Match(fill);
                        if (urlM.Success)
                        {
                            var id = urlM.Groups[1].Value.Trim();

                            XElement defE;
                            if (defs.TryGetValue(id, out defE))
                            {
                                var gradientShader = ReadGradient(defE);
                                if (gradientShader != null)
                                {
                                    // TODO: multiple shaders

                                    fillPaint.Shader = gradientShader;
                                    read             = true;
                                }
                                // else try another type (eg: image)
                            }
                            else
                            {
                                LogOrThrow($"Invalid fill url reference: {id}");
                            }
                        }

                        if (!read)
                        {
                            LogOrThrow($"Unsupported fill: {fill}");
                        }
                    }
                }

                // fill attributes
                var fillOpacity = GetString(style, "fill-opacity");
                if (!string.IsNullOrWhiteSpace(fillOpacity))
                {
                    if (fillPaint == null)
                    {
                        fillPaint = CreatePaint();
                    }

                    fillPaint.Color = fillPaint.Color.WithAlpha((byte)(ReadNumber(fillOpacity) * 255));
                }

                if (fillPaint != null)
                {
                    fillPaint.Color = fillPaint.Color.WithAlpha((byte)(fillPaint.Color.Alpha * elementOpacity));
                }
            }
        }
Пример #29
0
        public static void DrawSliderValue(this SKCanvas canvas, string text, float x, float y, float textSize, SKColor textColor, SKColor backgroundColor, int padding, int margin, string maxText, int count, int index, StackOrientation orientation, SKRect frame, bool useDashedEffect)
        {
            y = 0;

            using (var textPaint = new SKPaint())
            {
                textPaint.TextSize    = textSize;
                textPaint.Color       = textColor;
                textPaint.IsAntialias = true;
                textPaint.StrokeCap   = SKStrokeCap.Round;

                // Calculates the longest possible text
                SKRect textBounds = new SKRect();
                textPaint.MeasureText(maxText, ref textBounds);

                // Sets the width and height of the view
                var width  = textBounds.Width + padding;
                var height = textBounds.Height + padding;

                float xPosition, yPosition;

                if (orientation == StackOrientation.Vertical)
                {
                    if (x - (width / 2) < frame.Left)
                    {
                        xPosition = frame.Left;
                    }
                    else if (x + (width / 2) > frame.Right)
                    {
                        xPosition = frame.Right - width;
                    }
                    else
                    {
                        xPosition = x - (width / 2);
                    }

                    yPosition = y + (height * index) + (index * margin);
                }
                else
                {
                    var totalWidth = (width * count) + (count * margin);

                    if (totalWidth / 2 >= x - frame.Left)
                    {
                        xPosition = x + (index * width) + (index * margin);
                    }
                    else if (totalWidth / 2 >= frame.Right - x)
                    {
                        xPosition = x - totalWidth + (index * width) + (index * margin) + margin;
                    }
                    else
                    {
                        xPosition = x - ((totalWidth / 2) - (index * width) - (index * margin));
                    }

                    yPosition = y;
                }

                using (var backgroundPaint = new SKPaint())
                {
                    backgroundPaint.Color     = backgroundColor;
                    backgroundPaint.StrokeCap = SKStrokeCap.Round;

                    if (useDashedEffect)
                    {
                        backgroundPaint.PathEffect  = SKPathEffect.CreateDash(new float[] { 12, 12 }, 0);
                        backgroundPaint.Style       = SKPaintStyle.Stroke;
                        backgroundPaint.StrokeWidth = 8f;
                        backgroundPaint.IsStroke    = true;

                        textPaint.Color = backgroundColor;

                        xPosition += (useDashedEffect ? backgroundPaint.StrokeWidth / 2 : 0);
                        width     -= (useDashedEffect ? backgroundPaint.StrokeWidth : 0);

                        if (orientation == StackOrientation.Horizontal)
                        {
                            height -= backgroundPaint.StrokeWidth / 2;
                        }
                        else
                        {
                            yPosition += backgroundPaint.StrokeWidth / 2;
                        }
                    }
                    else
                    {
                        backgroundPaint.Style       = SKPaintStyle.StrokeAndFill;
                        backgroundPaint.StrokeWidth = 2f;
                    }

                    SKRect background = new SKRect(xPosition, yPosition, xPosition + width, yPosition + height);
                    canvas.DrawRect(background, backgroundPaint);

                    SKRect finalTextBounds = new SKRect();
                    textPaint.MeasureText(text, ref finalTextBounds);

                    canvas.DrawText(text, background.MidX - (finalTextBounds.Width / 2), background.MidY + (finalTextBounds.Height / 2), textPaint);
                }
            }
        }
Пример #30
0
        public void DrawMarker(int max)
        {
            var style = new SKPaint()
            {
                TextSize    = 28.0f,
                IsAntialias = true,
                Style       = SKPaintStyle.Stroke,
                Color       = (SKColor)0xFF4281A4,
                StrokeWidth = 2
            };

            _canvas.DrawLine(
                DrawParam.StartX,
                5,
                DrawParam.StartX + (5 * DrawParam.UnitX),
                5,
                style);

            for (int i = 0; i <= max; i++)
            {
                int x = i * DrawParam.UnitX + DrawParam.StartX;
                _canvas.DrawLine(
                    x,
                    5,
                    x,
                    DrawParam.MarkHeight,
                    style);
            }

            _timingMap = _timingDatas[0];

            var labelIndex = new List <int>();

            for (var index = 0; index < _timingMap.Timing.Length; index++)
            {
                if (_timingMap.Timing[index] == '|')
                {
                    labelIndex.Add(index);
                }
            }

            var pathStyle = new SKPaint()
            {
                TextSize    = 24.0f,
                Style       = SKPaintStyle.Stroke,
                Color       = SKColors.GreenYellow,
                StrokeWidth = 4,
                StrokeCap   = SKStrokeCap.Square,
                PathEffect  = SKPathEffect.CreateDash(new float[] { 1, 1 }, 2),
            };

            var path = new SKPath();

            foreach (var i in labelIndex)
            {
                Debug.WriteLine("marker position : " + i);
                path.MoveTo(
                    5 + DrawParam.StartX + i * DrawParam.UnitX,
                    8);

                path.LineTo(
                    5 + DrawParam.StartX + i * DrawParam.UnitX,
                    8 + (max / 2 * (DrawParam.UnitY + DrawParam.VerticalSpace))
                    );

                _canvas.DrawPath(path, pathStyle);
            }
        }