Пример #1
0
        private void DrawMultilineText(string text, SKPoint point, SKPaint paint)
        {
            if (text.Contains("\n"))
            {
                String[] lines = text.Replace("\r", "").Split('\n');

                foreach (var line in lines)
                {
                    _canvas?.DrawText(line, point, paint);

                    point.Y += paint.TextSize;
                }
            }
            else
            {
                _canvas?.DrawText(text, point, paint);
            }
        }
Пример #2
0
        private void DrawValueIndicator(SKCanvas canvas, int width, int height)
        {
            if (IndicatorValue < Minimum || IndicatorValue > Maximum)
            {
                return;
            }

            float indicatorPosition = (height - guageWidth * 2) * (1f - (IndicatorValue - Minimum) / (Maximum - Minimum)) + guageWidth;
            float verticalMargin    = guageWidth / 2 + regularStrokeWidth / 2;

            //Draw Indicator Line
            var start = new SKPoint(IndicatorDirection == "Right" ? guageWidth + 10 : width - guageWidth - 10, indicatorPosition);
            var end   = new SKPoint(IndicatorDirection == "Right" ? guageWidth + 40 : width - guageWidth - 40, indicatorPosition);

            canvas.DrawLine(start, end, indicatorStrokePaint);

            //Draw Value Label
            using (var textPaint = new SKPaint())
            {
                textPaint.TextSize    = (Device.RuntimePlatform == Device.Android) ? 36 : 20;
                textPaint.IsAntialias = true;
                textPaint.Color       = strokeColor;
                textPaint.IsStroke    = false;

                var indicatorText = IndicatorValue.ToString("0.0") + (!String.IsNullOrEmpty(IndicatorValueUnit) ? " " + IndicatorValueUnit : "");

                if (IndicatorDirection == "Right")
                {
                    canvas.DrawText(indicatorText, guageWidth + 40 + 10, indicatorPosition + 14, textPaint);
                }
                else
                {
                    float textWidth = textPaint.MeasureText(indicatorText);

                    canvas.DrawText(indicatorText, width - guageWidth - 40 - 10 - textWidth, indicatorPosition + 14, textPaint);
                }
            }

            //Fill the guage
            using (SKPath containerPath = new SKPath())
            {
                switch (IndicatorDirection)
                {
                case "Right":
                    containerPath.MoveTo(regularStrokeWidth / 2, indicatorPosition);
                    containerPath.LineTo(guageWidth + regularStrokeWidth / 2, indicatorPosition);
                    containerPath.LineTo(guageWidth + regularStrokeWidth / 2, height - verticalMargin);
                    containerPath.ArcTo(guageWidth / 2, guageWidth / 2, 0, SKPathArcSize.Large, SKPathDirection.Clockwise, regularStrokeWidth / 2, height - verticalMargin);
                    containerPath.Close();
                    break;

                case "Left":
                    containerPath.MoveTo(width - guageWidth - regularStrokeWidth / 2, indicatorPosition);
                    containerPath.LineTo(width - regularStrokeWidth / 2, indicatorPosition);
                    containerPath.LineTo(width - regularStrokeWidth / 2, height - verticalMargin);
                    containerPath.ArcTo(guageWidth / 2, guageWidth / 2, 0, SKPathArcSize.Large, SKPathDirection.Clockwise, width - guageWidth - regularStrokeWidth / 2, height - verticalMargin);
                    containerPath.Close();
                    break;
                }

                canvas.DrawPath(containerPath, fillPaint);
            }
        }
Пример #3
0
        public static void DrawCaptionLabels(this SKCanvas canvas, string label, SKColor labelColor, string value, SKColor valueColor, float textSize, SKPoint point, SKTextAlign horizontalAlignment)
        {
            var hasLabel      = !string.IsNullOrEmpty(label);
            var hasValueLabel = !string.IsNullOrEmpty(value);

            if (hasLabel || hasValueLabel)
            {
                var hasOffset     = hasLabel && hasValueLabel;
                var captionMargin = textSize * 0.60f;
                var space         = hasOffset ? captionMargin : 0;

                if (hasLabel)
                {
                    using (var paint = new SKPaint()
                    {
                        TextSize = textSize,
                        IsAntialias = true,
                        Color = labelColor,
                        IsStroke = false,
                        //TextAlign = horizontalAlignment,
                    })
                    {
                        var bounds = new SKRect();
                        var text   = label;
                        paint.MeasureText(text, ref bounds);

                        var y = point.Y - ((bounds.Top + bounds.Bottom) / 2) - space;


                        //canvas.DrawText(text, point.X, y, paint);

                        using (var tf = SKFontManager.Default.MatchCharacter('م'))
                            using (var shaper = new SKShaper(tf))
                                using (var paint1 = new SKPaint {
                                    TextSize = 30, Typeface = tf
                                })
                                {
                                    //canvas.Clear(SKColors.White);
                                    //canvas.DrawShapedText(shaper, "سلام", 100, 200, paint1);
                                    paint.Typeface = tf;
                                    var balaceValue = 0;
                                    if (horizontalAlignment == SKTextAlign.Right)
                                    {
                                        if (text.Length <= 5)
                                        {
                                            balaceValue = 60;
                                        }
                                        else
                                        {
                                            var factor = (System.Math.Abs(text.Length - 5));
                                            balaceValue = factor * 10 + 90;
                                        }
                                    }
                                    canvas.DrawShapedText(shaper, text, point.X - balaceValue, y, paint);
                                }
                    }
                }

                if (hasValueLabel)
                {
                    using (var paint = new SKPaint()
                    {
                        TextSize = textSize,
                        IsAntialias = true,
                        FakeBoldText = true,
                        Color = valueColor,
                        IsStroke = false,
                        TextAlign = horizontalAlignment,
                    })
                    {
                        var bounds = new SKRect();
                        var text   = value;
                        paint.MeasureText(text, ref bounds);

                        var y = point.Y - ((bounds.Top + bounds.Bottom) / 2) + space;

                        canvas.DrawText(text, point.X, y, paint);
                    }
                }
            }
        }
Пример #4
0
        private int DrawTables(SKBitmap pkImage, SKBitmap fkImage, Dictionary <string, SKBitmap> icons)
        {
            int currentHeight       = TopPadding;
            int currentRowMaxHeight = 0;
            int tableIndex          = 0;


            foreach (var dbTable in DBTableInfo)
            {
                int tableHeight = dbTable.FieldInfos.Count * RowHeight;
                currentRowMaxHeight = Math.Max(currentRowMaxHeight, tableHeight);

                int countTable = 0;
                Canvas.DrawText(dbTable.TableName, new SKPoint(LeftPadding + (TableWidth + LeftPadding) * (tableIndex % ColumnCount), TopPadding + countTable * RowHeight + currentHeight - 8), DrawingHelper.LargeTextPaint);


                foreach (var field in dbTable.FieldInfos)
                {
                    int tableCellX = LeftPadding + (TableWidth + LeftPadding) * (tableIndex % ColumnCount);
                    int tableCellY = TopPadding + countTable * RowHeight + currentHeight;

                    // For PK/FK Images
                    int x = tableCellX + TableWidth - 40;
                    int y = tableCellY + 8;

                    if (field.IsPrimaryKey)
                    {
                        Canvas.DrawBitmap(pkImage, new SKPoint(x, y));

                        //primaryKeys.Add(dbTable.TableName, new Point(x + 35, y + 4));
                    }

                    //Brush brush = new SolidBrush(Color.FromArgb(128, 137, 153, 162)); // TODO move above

                    // TODO Find coresponding function
                    //Canvas.FillRect(brush, new SKRect(LeftPadding + (TableWidth + LeftPadding) * (tableIndex % ColumnCount), TopPadding + countTable * RowHeight + currentHeight, TableWidth, RowHeight));

                    // Border
                    Canvas.DrawRect(new SKRect(tableCellX, tableCellY, tableCellX + TableWidth, tableCellY + RowHeight), new SKPaint()
                    {
                        Color = new SKColor(255, 255, 255),
                        Style = SKPaintStyle.Stroke
                    });

                    Canvas.DrawRect(new SKRect(tableCellX, tableCellY, tableCellX + TableWidth, tableCellY + RowHeight), new SKPaint()
                    {
                        Color = new SKColor(255, 255, 255, 50)
                    });

                    var type = field.Type.Replace("EGER", "");

                    Canvas.DrawText($"{field.Name} ({type}{(field.Nullable ? ", NULL" : "")})", new SKPoint(tableCellX + 25 /* for the icon*/ + 8, tableCellY + RowHeight / 2 + (int)(DrawingHelper.TitleTextPaint.TextSize / 2)), DrawingHelper.TitleTextPaint);

                    if (icons.ContainsKey(field.GeneralType))
                    {
                        var bitmap = icons[field.GeneralType];
                        // TODO the resize once
                        var icon = bitmap.Resize(new SKSizeI(25, 25), SKFilterQuality.High);

                        Canvas.DrawBitmap(icon, tableCellX + 5, tableCellY + 5);
                    }

                    if (field.IsForeignKey && !field.IsPrimaryKey)
                    {
                        Canvas.DrawBitmap(fkImage, x, y);

                        //if (primaryKeys.ContainsKey(field.ForeignKeyInfo.ToTable))
                        //{
                        //Graphics.DrawLine(p, new Point(leftPadding + (width + leftPadding) * count + width - 35, topPadding + countTable * height + custHeight + 8), primaryKeys[field.ForeignKeyInfo.ToTable]);
                        //}
                    }
                    countTable++;
                }

                tableIndex++;

                if (tableIndex % ColumnCount == 0)
                {
                    currentHeight      += currentRowMaxHeight + TopPadding;
                    currentRowMaxHeight = 0;
                }
            }

            currentHeight += currentRowMaxHeight + TopPadding * 2;
            return(currentHeight);
        }
Пример #5
0
        internal void Draw(DrawingContextImpl context,
                           SKCanvas canvas,
                           SKPoint origin,
                           DrawingContextImpl.PaintWrapper foreground,
                           bool canUseLcdRendering)
        {
            /* TODO: This originated from Native code, it might be useful for debugging character positions as
             * we improve the FormattedText support. Will need to port this to C# obviously. Rmove when
             * not needed anymore.
             *
             *  SkPaint dpaint;
             *  ctx->Canvas->save();
             *  ctx->Canvas->translate(origin.fX, origin.fY);
             *  for (int c = 0; c < Lines.size(); c++)
             *  {
             *      dpaint.setARGB(255, 0, 0, 0);
             *      SkRect rc;
             *      rc.fLeft = 0;
             *      rc.fTop = Lines[c].Top;
             *      rc.fRight = Lines[c].Width;
             *      rc.fBottom = rc.fTop + LineOffset;
             *      ctx->Canvas->drawRect(rc, dpaint);
             *  }
             *  for (int c = 0; c < Length; c++)
             *  {
             *      dpaint.setARGB(255, c % 10 * 125 / 10 + 125, (c * 7) % 10 * 250 / 10, (c * 13) % 10 * 250 / 10);
             *      dpaint.setStyle(SkPaint::kFill_Style);
             *      ctx->Canvas->drawRect(Rects[c], dpaint);
             *  }
             *  ctx->Canvas->restore();
             */
            using (var paint = _paint.Clone())
            {
                IDisposable currd          = null;
                var         currentWrapper = foreground;
                SKPaint     currentPaint   = null;
                try
                {
                    ApplyWrapperTo(ref currentPaint, foreground, ref currd, paint, canUseLcdRendering);
                    bool hasCusomFGBrushes = _foregroundBrushes.Any();

                    for (int c = 0; c < _skiaLines.Count; c++)
                    {
                        AvaloniaFormattedTextLine line = _skiaLines[c];

                        float x = TransformX(origin.X, 0, paint.TextAlign);

                        if (!hasCusomFGBrushes)
                        {
                            var subString = Text.Substring(line.Start, line.Length);
                            canvas.DrawText(subString, x, origin.Y + line.Top + _lineOffset, paint);
                        }
                        else
                        {
                            float  currX = x;
                            string subStr;
                            float  measure;
                            int    len;
                            float  factor;
                            switch (paint.TextAlign)
                            {
                            case SKTextAlign.Left:
                                factor = 0;
                                break;

                            case SKTextAlign.Center:
                                factor = 0.5f;
                                break;

                            case SKTextAlign.Right:
                                factor = 1;
                                break;

                            default:
                                throw new ArgumentOutOfRangeException();
                            }

                            var textLine = Text.Substring(line.Start, line.Length);
                            currX -= textLine.Length == 0 ? 0 : paint.MeasureText(textLine) * factor;

                            for (int i = line.Start; i < line.Start + line.Length;)
                            {
                                var fb = GetNextForegroundBrush(ref line, i, out len);

                                if (fb != null)
                                {
                                    //TODO: figure out how to get the brush size
                                    currentWrapper = context.CreatePaint(fb, new Size());
                                }
                                else
                                {
                                    if (!currentWrapper.Equals(foreground))
                                    {
                                        currentWrapper.Dispose();
                                    }
                                    currentWrapper = foreground;
                                }

                                subStr  = Text.Substring(i, len);
                                measure = paint.MeasureText(subStr);
                                currX  += measure * factor;

                                ApplyWrapperTo(ref currentPaint, currentWrapper, ref currd, paint, canUseLcdRendering);

                                canvas.DrawText(subStr, currX, origin.Y + line.Top + _lineOffset, paint);

                                i     += len;
                                currX += measure * (1 - factor);
                            }
                        }
                    }
                }
                finally
                {
                    if (!currentWrapper.Equals(foreground))
                    {
                        currentWrapper.Dispose();
                    }
                    currd?.Dispose();
                }
            }
        }
Пример #6
0
        private void DrawPrimitive(SKCanvas canvas, Matrix4 transform, SKPaint paint, IPrimitive primitive)
        {
            var scale          = ActualHeight / Workspace.ActiveViewPort.ViewHeight;
            var oldStrokeWidth = paint.StrokeWidth;

            switch (primitive.Kind)
            {
            case PrimitiveKind.Ellipse:
            {
                paint.IsStroke = true;
                var el = (PrimitiveEllipse)primitive;
                paint.StrokeWidth += (float)(el.Thickness * scale);
                using (var path = new SKPath())
                {
                    path.MoveTo(transform.Transform(el.StartPoint()).ToSKPoint());
                    var startAngle = (el.StartAngle + 1.0).CorrectAngleDegrees();
                    var endAngle   = el.EndAngle.CorrectAngleDegrees();
                    if (endAngle < startAngle)
                    {
                        endAngle += MathHelper.ThreeSixty;
                    }

                    for (var angle = startAngle; angle <= endAngle; angle += 1.0)
                    {
                        path.LineTo(transform.Transform(el.GetPoint(angle)).ToSKPoint());
                    }

                    path.LineTo(transform.Transform(el.EndPoint()).ToSKPoint());
                    canvas.DrawPath(path, paint);
                }
                break;
            }

            case PrimitiveKind.Line:
            {
                paint.IsStroke = true;
                var line = (PrimitiveLine)primitive;
                paint.StrokeWidth += (float)(line.Thickness * scale);
                var p1 = transform.Transform(line.P1);
                var p2 = transform.Transform(line.P2);
                canvas.DrawLine((float)p1.X, (float)p1.Y, (float)p2.X, (float)p2.Y, paint);
                break;
            }

            case PrimitiveKind.Point:
            {
                paint.IsStroke = true;
                var point         = (PrimitivePoint)primitive;
                var loc           = transform.Transform(point.Location);
                var pointSizeHalf = Workspace.SettingsService.GetValue <double>(WpfSettingsProvider.PointSize) * 0.5;
                canvas.DrawLine((float)(loc.X - pointSizeHalf), (float)loc.Y, (float)(loc.X + pointSizeHalf), (float)loc.Y, paint);
                canvas.DrawLine((float)loc.X, (float)(loc.Y - pointSizeHalf), (float)loc.X, (float)(loc.Y + pointSizeHalf), paint);
                break;
            }

            case PrimitiveKind.Text:
            {
                paint.IsStroke = false;
                var text = (PrimitiveText)primitive;
                var loc  = transform.Transform(text.Location);
                paint.TextSize = (float)((ActualHeight / Workspace.ActiveViewPort.ViewHeight) * text.Height);
                canvas.Save();
                canvas.RotateDegrees(-(float)text.Rotation, (float)loc.X, (float)loc.Y);
                canvas.DrawText(text.Value, (float)loc.X, (float)loc.Y, paint);
                canvas.Restore();
                break;
            }
            }

            paint.StrokeWidth = oldStrokeWidth;
        }
Пример #7
0
        private SKBitmap BuildThumbCollageBitmap(IReadOnlyList <string> paths, int width, int height, string?libraryName)
        {
            var bitmap = new SKBitmap(width, height);

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

            using var backdrop = GetNextValidImage(paths, 0, out _);
            if (backdrop == null)
            {
                return(bitmap);
            }

            // resize to the same aspect as the original
            var backdropHeight = Math.Abs(width * backdrop.Height / backdrop.Width);

            using var residedBackdrop = SkiaEncoder.ResizeImage(backdrop, new SKImageInfo(width, backdropHeight, backdrop.ColorType, backdrop.AlphaType, backdrop.ColorSpace));
            // draw the backdrop
            canvas.DrawImage(residedBackdrop, 0, 0);

            // draw shadow rectangle
            var paintColor = new SKPaint
            {
                Color = SKColors.Black.WithAlpha(0x78),
                Style = SKPaintStyle.Fill
            };

            canvas.DrawRect(0, 0, width, height, paintColor);

            var typeFace = SKTypeface.FromFamilyName("sans-serif", SKFontStyleWeight.Bold, SKFontStyleWidth.Normal, SKFontStyleSlant.Upright);

            // use the system fallback to find a typeface for the given CJK character
            var nonCjkPattern = @"[^\p{IsCJKUnifiedIdeographs}\p{IsCJKUnifiedIdeographsExtensionA}\p{IsKatakana}\p{IsHiragana}\p{IsHangulSyllables}\p{IsHangulJamo}]";
            var filteredName  = Regex.Replace(libraryName ?? string.Empty, nonCjkPattern, string.Empty);

            if (!string.IsNullOrEmpty(filteredName))
            {
                typeFace = SKFontManager.Default.MatchCharacter(null, SKFontStyleWeight.Bold, SKFontStyleWidth.Normal, SKFontStyleSlant.Upright, null, filteredName[0]);
            }

            // draw library name
            var textPaint = new SKPaint
            {
                Color       = SKColors.White,
                Style       = SKPaintStyle.Fill,
                TextSize    = 112,
                TextAlign   = SKTextAlign.Center,
                Typeface    = typeFace,
                IsAntialias = true
            };

            // scale down text to 90% of the width if text is larger than 95% of the width
            var textWidth = textPaint.MeasureText(libraryName);

            if (textWidth > width * 0.95)
            {
                textPaint.TextSize = 0.9f * width * textPaint.TextSize / textWidth;
            }

            canvas.DrawText(libraryName, width / 2f, (height / 2f) + (textPaint.FontMetrics.XHeight / 2), textPaint);

            return(bitmap);
        }
Пример #8
0
        private void DrawContent(SKCanvas canvas, int width, int height)
        {
            // Set transforms
            canvas.Translate(width / 2, height / 2); // center is 0,0

            // Outer
            canvas.DrawCircle(0, 0, 100, _outerCircleFillPaint);

            // Hour and minute
            float hourShiftAngle    = SweepAngle / HourIndicators;
            float minutesShiftAngle = (hourShiftAngle / MinutesInHour) * MinutesIndicators;

            if (Math.Abs(minutesShiftAngle) < 0.01)
            {
                throw new Exception("Wrong value of minutes");
            }

            canvas.RotateDegrees(StartAngle);

            canvas.Save();

            int   hoursCounter = 0;
            float radius       = Math.Min(width / 2, height / 2) - 2 * ExplodeOffset;

            for (float angle = 0; angle < 360; angle += minutesShiftAngle)
            {
                if (angle <= HourIndicators * hourShiftAngle)
                {
                    var linePaint  = angle % hourShiftAngle == 0 ? _hourStrokePaint : _minuteStrokePaint;
                    var lineYStart = angle % hourShiftAngle == 0 ? -radius - 20 : -radius - 40;
                    var lineYEnd   = -radius - 70;

                    canvas.DrawLine(0, lineYStart, 0, lineYEnd, linePaint);

                    if (angle % hourShiftAngle == 0)
                    {
                        using (var paint = new SKPaint())
                        {
                            //paint.Typeface = SKTypeface.FromFamilyName(null, SKTypefaceStyle.Bold);
                            paint.TextSize = HourTextSize;

                            canvas.DrawText(hoursCounter.ToString(CultureInfo.InvariantCulture), new SKPoint(-20, lineYStart + 100), paint);
                            hoursCounter += 1;
                        }
                    }
                }
                else
                {
                    break;
                }

                canvas.RotateDegrees(minutesShiftAngle);
            }

            canvas.Restore();

            // Duration indicator
            var durationInMinutes = Duration / 60;
            var rotateAngle       = Convert.ToSingle(durationInMinutes * SweepAngle / (HourIndicators * MinutesInHour));

            canvas.RotateDegrees(rotateAngle);

            var durationIndicatorShadowPath = SKPath.ParseSvgPathData($"M -8 0 L -2 {-radius - 30} L 2 {-radius - 30} L 14 0 Z");
            var durationIndicatorShadow     = SKPath.ParseSvgPathData($"M -8 0 L -2 {-radius - 30} L 2 {-radius - 30} L 8 0 Z");

            canvas.DrawPath(durationIndicatorShadowPath, _grayStrokePaint);
            canvas.DrawPath(durationIndicatorShadow, _redStrokePaint);

            // Inner circle
            canvas.DrawCircle(0, 0, 50, _innerCircleFillPaint);
        }
Пример #9
0
        protected override void OnPaintSurface(SKPaintSurfaceEventArgs e)
        {
            Trace.WriteLine($"{GetType().Name} OnPaintSurface");
            SKImageInfo info    = e.Info;
            SKSurface   surface = e.Surface;
            SKCanvas    canvas  = surface.Canvas;

            RadiusDefault = Math.Max(info.Width, info.Height) / 2;
            if (Radius == 0)
            {
                Radius = RadiusDefault;
            }

            // 押下状態では影を大きくする
            var seed        = Math.Min(info.Rect.Width, info.Rect.Height);
            int bodyDelta   = seed / 10;
            var bodyRect    = new SKRectI(info.Rect.Left + bodyDelta, info.Rect.Top + bodyDelta, info.Rect.Right - bodyDelta, info.Rect.Bottom - bodyDelta);
            int shadowDelta = IsPressed ? 0 : seed / 20;
            var shadowRect  = new SKRectI(info.Rect.Left + shadowDelta, info.Rect.Top + shadowDelta, info.Rect.Right - shadowDelta, info.Rect.Bottom - shadowDelta);
            var shadowColor = SKColors.DarkGray;
            var sunnyColor  = SKColors.Transparent;

            canvas.Clear();

            // 上下の影
            using (var paint = new SKPaint())
            {
                float start = (float)(bodyRect.Top - shadowRect.Top) / shadowRect.Height;
                float end   = 1 - start;
                var   rect  = new SKRectI(bodyRect.Left, shadowRect.Top, bodyRect.Right, shadowRect.Bottom);

                paint.Shader = SKShader.CreateLinearGradient(
                    new SKPoint(rect.MidX, rect.Top),
                    new SKPoint(rect.MidX, rect.Bottom),
                    new SKColor[] { sunnyColor, shadowColor, shadowColor, sunnyColor },
                    new float[] { 0, start, end, 1 },
                    SKShaderTileMode.Clamp);
                canvas.DrawRect(rect, paint);
            }

            // 左右の影
            using (var paint = new SKPaint())
            {
                float start = (float)(bodyRect.Left - shadowRect.Left) / shadowRect.Width;
                float end   = 1 - start;
                var   rect  = new SKRectI(shadowRect.Left, bodyRect.Top, shadowRect.Right, bodyRect.Bottom);

                paint.Shader = SKShader.CreateLinearGradient(
                    new SKPoint(rect.Left, rect.MidY),
                    new SKPoint(rect.Right, rect.MidY),
                    new SKColor[] { sunnyColor, shadowColor, shadowColor, sunnyColor },
                    new float[] { 0, start, end, 1 },
                    SKShaderTileMode.Clamp);
                canvas.DrawRect(rect, paint);
            }

            // 四隅 左上
            using (var paint = new SKPaint())
            {
                var rect = new SKRectI(shadowRect.Left, shadowRect.Top, bodyRect.Left, bodyRect.Top);

                paint.Shader = SKShader.CreateRadialGradient(
                    new SKPoint(rect.Right, rect.Bottom),
                    rect.Width,
                    new SKColor[] { shadowColor, sunnyColor },
                    null,
                    SKShaderTileMode.Clamp);
                canvas.DrawRect(rect, paint);
            }
            // 四隅 右上
            using (var paint = new SKPaint())
            {
                var rect = new SKRectI(bodyRect.Right, shadowRect.Top, shadowRect.Right, bodyRect.Top);

                paint.Shader = SKShader.CreateRadialGradient(
                    new SKPoint(rect.Left, rect.Bottom),
                    rect.Width,
                    new SKColor[] { shadowColor, sunnyColor },
                    null,
                    SKShaderTileMode.Clamp);
                canvas.DrawRect(rect, paint);
            }
            // 四隅 左下
            using (var paint = new SKPaint())
            {
                var rect = new SKRectI(shadowRect.Left, bodyRect.Bottom, bodyRect.Left, shadowRect.Bottom);

                paint.Shader = SKShader.CreateRadialGradient(
                    new SKPoint(rect.Right, rect.Top),
                    rect.Width,
                    new SKColor[] { shadowColor, sunnyColor },
                    null,
                    SKShaderTileMode.Clamp);
                canvas.DrawRect(rect, paint);
            }
            // 四隅 右下
            using (var paint = new SKPaint())
            {
                var rect = new SKRectI(bodyRect.Right, bodyRect.Bottom, shadowRect.Right, shadowRect.Bottom);

                paint.Shader = SKShader.CreateRadialGradient(
                    new SKPoint(rect.Left, rect.Top),
                    rect.Width,
                    new SKColor[] { shadowColor, sunnyColor },
                    null,
                    SKShaderTileMode.Clamp);
                canvas.DrawRect(rect, paint);
            }

            // 本体
            using (var paint = new SKPaint())
            {
                // 非活性状態ではグレー
                var centerColor = IsEnabled ? CenterColor.ToSKColor() : SKColors.WhiteSmoke;
                var edgeColor   = IsEnabled ? EdgeColor.ToSKColor() : SKColors.LightGray;

                // プラットフォームにより影のサイズが異なるため切れてしまう
                //var sigma = IsPressed ? 4 : 1;
                //paint.ImageFilter = SKImageFilter.CreateDropShadow(0, 0, sigma, sigma, SKColors.Black, SKDropShadowImageFilterShadowMode.DrawShadowAndForeground);

                paint.Shader = SKShader.CreateRadialGradient(
                    new SKPoint(info.Rect.MidX, info.Rect.MidY),
                    Radius,
                    new SKColor[] { centerColor, edgeColor },
                    null,
                    SKShaderTileMode.Clamp);
                canvas.DrawRect(bodyRect, paint);
            }

            // 文字
            using (var paint = new SKPaint())
            {
                paint.Color       = IsEnabled ? SKColors.Black : SKColors.Gray;
                paint.Typeface    = SKTypeface.FromFamilyName("Arial", SKTypefaceStyle.Bold);
                paint.IsAntialias = true;

                // 見やすくならない
                //paint.ImageFilter = SKImageFilter.CreateDropShadow(2, 2, 2, 2, SKColors.Black, SKDropShadowImageFilterShadowMode.DrawShadowAndForeground);

                var textBounds = new SKRect();
                paint.MeasureText(Text, ref textBounds);

                float height = textBounds.Height;
                paint.TextSize = 0.4f * bodyRect.Height * paint.TextSize / height;
                paint.MeasureText(Text, ref textBounds);

                float xText = bodyRect.Width / 2 - textBounds.MidX + bodyDelta;
                float yText = bodyRect.Height / 2 - textBounds.MidY + bodyDelta;

                canvas.DrawText(Text, xText, yText, paint);
            }
        }
        private void PaintSurface(object sender, SKPaintSurfaceEventArgs args, computeLensRequestSideDTO computeLensRequestSideDTO, computeLensResponseSideDTO computeLensResponseSideDTO)
        {
            SKImageInfo info    = args.Info;
            SKSurface   surface = args.Surface;
            SKCanvas    canvas  = surface.Canvas;

            canvas.Clear();

            SKPaint blackSKPaint = new SKPaint
            {
                Style = SKPaintStyle.Fill,
                Color = Color.Black.ToSKColor(),
            };

            canvas.DrawRect(new SKRect(0, 0, info.Width, info.Height), blackSKPaint);

            if (computeLensResponseSideDTO.points != null & computeLensResponseSideDTO.points.Any())
            {
                ICollection <analyzedPointDTO> points = computeLensResponseSideDTO.points.Where(point => point is analyzedPointDTO && Math.Abs(point.x) <= computeLensRequestSideDTO.horizontalDiameter / 2.0 && Math.Abs(point.y) <= computeLensRequestSideDTO.verticalDiameter / 2.0).Select(point => point as analyzedPointDTO).ToList();

                double maxCylinder   = points.Select(point => point.cylinderMap).Max();
                double minCylinder   = points.Select(point => point.cylinderMap).Min();
                double cylinderRange = (maxCylinder - minCylinder) / 6.0;

                if (cylinderRange > 0)
                {
                    double doubleCylinderRange = cylinderRange * 2;
                    double tripleCylinderRange = cylinderRange * 3;
                    double fiveCylinderRange   = cylinderRange * 5;

                    double centerX = info.Width / 2.0;
                    double centerY = info.Height / 2.0;

                    int sqrt = Convert.ToInt32(Math.Sqrt(points.Count));
                    int side = (sqrt - 1) / 2;

                    double bitmapSide = Math.Min(info.Width, info.Height) / 2.0;

                    double sqrtRange       = sqrt / 6.0;
                    double doubleSqrtRange = sqrtRange * 2;
                    double tripleSqrtRange = sqrtRange * 3;
                    double fiveSqrtRange   = sqrtRange * 5;

                    using (SKBitmap bitmap = new SKBitmap(1, sqrt))
                    {
                        for (int i = sqrt - 1; i >= 0; i--)
                        {
                            SKColor color = Color.Black.ToSKColor();

                            switch (Math.Floor(i / sqrtRange))
                            {
                            case 0:
                                color = Color.FromRgb(Convert.ToInt32(Math.Round(i / sqrtRange * 255)), Convert.ToInt32(Math.Round(i / sqrtRange * 255)), 255).ToSKColor();
                                break;

                            case 1:
                                color = Color.FromRgb(Convert.ToInt32(Math.Round((doubleSqrtRange - i) / sqrtRange * 255)), 255, 255).ToSKColor();
                                break;

                            case 2:
                                color = Color.FromRgb(0, 255, Convert.ToInt32(Math.Round((tripleSqrtRange - i) / sqrtRange * 255))).ToSKColor();
                                break;

                            case 3:
                                color = Color.FromRgb(Convert.ToInt32(Math.Round((i - tripleSqrtRange) / sqrtRange * 255)), 255, 0).ToSKColor();
                                break;

                            case 4:
                                color = Color.FromRgb(255, Convert.ToInt32(Math.Round((fiveSqrtRange - i) / sqrtRange * 255)), 0).ToSKColor();
                                break;

                            default:
                                color = Color.FromRgb(255, 0, Convert.ToInt32(Math.Round((i - fiveSqrtRange) / sqrtRange * 255))).ToSKColor();
                                break;
                            }

                            bitmap.SetPixel(0, i, color);
                        }

                        canvas.DrawBitmap(bitmap.Resize(new SKImageInfo(Convert.ToInt32(bitmapSide / 6), Convert.ToInt32(bitmapSide)), SKBitmapResizeMethod.Mitchell), new SKRect(Convert.ToSingle(info.Width - bitmapSide / 6), 0, Convert.ToSingle(info.Width), info.Height));
                    }

                    blackSKPaint.TextSize = info.Height / 32;

                    float textRange = (info.Height - blackSKPaint.TextSize * 3) / 6;

                    canvas.DrawText(string.Format("{0:N2}", minCylinder), Convert.ToSingle(info.Width - bitmapSide / 8), blackSKPaint.TextSize * 2, blackSKPaint);
                    canvas.DrawText(string.Format("{0:N2}", minCylinder + cylinderRange), Convert.ToSingle(info.Width - bitmapSide / 8), blackSKPaint.TextSize * 2 + textRange, blackSKPaint);
                    canvas.DrawText(string.Format("{0:N2}", minCylinder + cylinderRange * 2), Convert.ToSingle(info.Width - bitmapSide / 8), blackSKPaint.TextSize * 2 + textRange * 2, blackSKPaint);
                    canvas.DrawText(string.Format("{0:N2}", minCylinder + cylinderRange * 3), Convert.ToSingle(info.Width - bitmapSide / 8), blackSKPaint.TextSize * 2 + textRange * 3, blackSKPaint);
                    canvas.DrawText(string.Format("{0:N2}", minCylinder + cylinderRange * 4), Convert.ToSingle(info.Width - bitmapSide / 8), blackSKPaint.TextSize * 2 + textRange * 4, blackSKPaint);
                    canvas.DrawText(string.Format("{0:N2}", minCylinder + cylinderRange * 5), Convert.ToSingle(info.Width - bitmapSide / 8), blackSKPaint.TextSize * 2 + textRange * 5, blackSKPaint);
                    canvas.DrawText(string.Format("{0:N2}", maxCylinder), Convert.ToSingle(info.Width - bitmapSide / 8), blackSKPaint.TextSize * 2 + textRange * 6, blackSKPaint);

                    using (SKBitmap bitmap = new SKBitmap(sqrt, sqrt))
                    {
                        foreach (analyzedPointDTO point in points)
                        {
                            SKColor color = Color.Black.ToSKColor();

                            double value = point.cylinderMap - minCylinder;

                            switch (Math.Floor(value / cylinderRange))
                            {
                            case 0:
                                color = Color.FromRgb(Convert.ToInt32(Math.Round(value / cylinderRange * 255)), Convert.ToInt32(Math.Round(value / cylinderRange * 255)), 255).ToSKColor();
                                break;

                            case 1:
                                color = Color.FromRgb(Convert.ToInt32(Math.Round((doubleCylinderRange - value) / cylinderRange * 255)), 255, 255).ToSKColor();
                                break;

                            case 2:
                                color = Color.FromRgb(0, 255, Convert.ToInt32(Math.Round((tripleCylinderRange - value) / cylinderRange * 255))).ToSKColor();
                                break;

                            case 3:
                                color = Color.FromRgb(Convert.ToInt32(Math.Round((value - tripleCylinderRange) / cylinderRange * 255)), 255, 0).ToSKColor();
                                break;

                            case 4:
                                color = Color.FromRgb(255, Convert.ToInt32(Math.Round((fiveCylinderRange - value) / cylinderRange * 255)), 0).ToSKColor();
                                break;

                            default:
                                color = Color.FromRgb(255, 0, Convert.ToInt32(Math.Round((value - fiveCylinderRange) / cylinderRange * 255))).ToSKColor();
                                break;
                            }

                            bitmap.SetPixel(Convert.ToInt32(side - point.x), Convert.ToInt32(side - point.y), color);
                        }

                        using (SKPath path = new SKPath())
                        {
                            path.AddCircle(Convert.ToSingle(centerX), Convert.ToSingle(centerY), Convert.ToSingle(bitmapSide * 5 / 6));
                            canvas.ClipPath(path, SKClipOperation.Intersect);
                        }

                        canvas.DrawBitmap(bitmap.Resize(new SKImageInfo(Convert.ToInt32(bitmapSide * 5 / 6), Convert.ToInt32(bitmapSide * 5 / 6)), SKBitmapResizeMethod.Mitchell), new SKRect(Convert.ToSingle(centerX - bitmapSide * 5 / 6), Convert.ToSingle(centerY - bitmapSide * 5 / 6), Convert.ToSingle(centerX + bitmapSide * 5 / 6), Convert.ToSingle(centerY + bitmapSide * 5 / 6)));
                    }
                }
            }
        }
Пример #11
0
        /// <summary>
        /// Draws a block of text onto the document and returns the height of that block.
        /// </summary>
        /// <param name="canvas">The skia canvas to draw onto.</param>
        /// <param name="text">The text to be printed onto the document.</param>
        /// <param name="y">The y position of the text block.</param>
        /// <param name="typeface">The font to be used for drawing the text.</param>
        /// <param name="textSize">The size of the text.</param>
        /// <param name="color">The color to be used for drawing the text.</param>
        /// <param name="textAlign">The alignment for the text to be drawn.</param>
        /// <param name="lineHeightFactor">A value indicating the line heigt. The default line heigt factor is 1.</param>
        /// <returns>Returns the height of the text block which was drawn to the document.</returns>
        private static float DrawTextBlock(SKCanvas canvas, string text, float y, SKTypeface typeface, float textSize,
                                           SKColor color, SKTextAlign textAlign = SKTextAlign.Center, float lineHeightFactor = 1.0f)
        {
            List <string> lineBreakSequences = new List <string>()
            {
                "\r", "\n", "\r\n"
            };

            using (var paint = new SKPaint())
            {
                paint.Typeface    = typeface;
                paint.TextSize    = textSize;
                paint.IsAntialias = true;
                paint.Color       = color;
                paint.TextAlign   = textAlign;

                float blockWidth = PAGE_WIDTH - (MARGIN_LEFT * 2);

                // Define x position according to chosen text alignment
                float xPos = 0f;
                switch (textAlign)
                {
                case SKTextAlign.Left:
                    xPos = MARGIN_LEFT;
                    break;

                case SKTextAlign.Center:
                    xPos = PAGE_WIDTH / 2;
                    break;

                case SKTextAlign.Right:
                    xPos = PAGE_WIDTH - MARGIN_LEFT;
                    break;
                }

                // Measure the height of one line of text
                SKRect bounds = new SKRect();
                paint.MeasureText(text, ref bounds);
                float lineHeight = bounds.Height * lineHeightFactor;

                // Now loop through all the tokens and build the
                // text block, adding new lines when we're either
                // out of space or when a newline if forced in the
                // token list.
                int           lines  = 1;
                StringBuilder line   = new StringBuilder();
                var           tokens = Tokenize(text);

                for (int i = 0; i < tokens.Count; i++)
                {
StartLine:
                    var token = tokens[i];
                    float totalLineWidth = 0;

                    if (token != null && token != "")
                    {
                        totalLineWidth = line.Length > 0 ?
                                         paint.MeasureText(line + " " + token) :
                                         paint.MeasureText(token);
                    }

                    if (totalLineWidth >= blockWidth || token == null)
                    {
                        canvas.DrawText(line.ToString(), xPos, y, paint);
                        line.Clear();
                        lines++;
                        y += lineHeight;
                        if (token != null)
                        {
                            goto StartLine;
                        }
                    }
                    else
                    {
                        if (line.Length != 0)
                        {
                            line.Append(" ");
                        }
                        line.Append(token);

                        if (i == tokens.Count - 1) // Last word
                        {
                            canvas.DrawText(line.ToString(), xPos, y, paint);
                            line.Clear();
                            lines++;
                            y += lineHeight;
                        }
                    }
                }

                // Return the total height of the text block
                return(lines * lineHeight);
            }
        }
Пример #12
0
        /*public SKBitmap B(List<Section> sections, Dictionary<Section, SKBitmap> bitmaps)
         * {
         *  List<int> featured = new List<int>();
         *  List<int> others = new List<int>();
         *
         *  int featuredCount = 0;
         *
         *  foreach (var section in sections)
         *  {
         *      if (section.SectionId.Contains("Featured"))
         *      {
         *          featured.Add(bitmaps.First(predicate: x => x.Key.SectionId == section.SectionId).Value.Width);
         *          featuredCount++;
         *          continue;
         *      }
         *      else //if (section.SectionId.Contains("Daily"))
         *      {
         *          others.Add(bitmaps.First(predicate: x => x.Key.SectionId == section.SectionId).Value.Width);
         *          continue;
         *      }
         *  };
         *
         *  int columnCount = featured.Count > 0 ? 2 : 1;
         *
         *  int width = columnCount * featured.Max();
         *  int featuredHeight = 0;
         *  int othersHeight = 0;
         *
         *  bitmaps.ToList().ForEach(pair =>
         *  {
         *      if (pair.Key.SectionId.Contains("Featured")) featuredHeight += pair.Value.Height;
         *      else othersHeight += pair.Value.Height;
         *  });
         *
         *  int height = Math.Max(featuredHeight, othersHeight) + 250;
         *
         *  int ratio = 0;
         *
         *  int fullHeight = 0;
         *  int fullWidth = 0;
         *
         *  if (height >= width) ratio = height / 9;
         *  else ratio = width / 16;
         *
         *  fullHeight = ratio * 9;
         *  fullWidth = ratio * 16;
         *
         *  var full = new SKBitmap(fullWidth, fullHeight);
         *
         *  using (var merge = new SKBitmap(width, height))
         *  {
         *      using (var c = new SKCanvas(merge))
         *      {
         *          int y = 0;
         *          int x = 0;
         *          int i = 0;
         *
         *          sections.ToList().ForEach(section =>
         *          {
         *              var bitmap = bitmaps.First(predicate: x => x.Key.SectionId == section.SectionId).Value;
         *
         *              c.DrawBitmap(bitmap, x, y);
         *              y += bitmap.Height;
         *              i++;
         *
         *              if (i == featuredCount)
         *              {
         *                  y = 0;
         *                  x += width / columnCount;
         *              }
         *          });
         *      }
         *
         *      using (var c = new SKCanvas(full))
         *      {
         *          c.DrawRect(0, 0, full.Width, full.Height,
         *              new SKPaint
         *              {
         *                  IsAntialias = true,
         *                  FilterQuality = SKFilterQuality.High,
         *                  Color = new SKColor(40, 40, 40)
         *              });
         *
         *          c.DrawBitmap(merge, (full.Width - merge.Width) / 2, 0,
         *              new SKPaint
         *              {
         *                  IsAntialias = true,
         *                  FilterQuality = SKFilterQuality.High
         *              });
         *
         *          var textPaint = new SKPaint
         *          {
         *              IsAntialias = true,
         *              FilterQuality = SKFilterQuality.High,
         *              TextSize = 200,
         *              Color = SKColors.White,
         *              Typeface = ChicTypefaces.BurbankBigRegularBlack,
         *              ImageFilter = SKImageFilter.CreateDropShadow(0, 0, 10, 10, SKColors.Black)
         *          };
         *
         *          var sacText = "Code 'Chic' #Ad";
         *
         *          c.DrawText(sacText, (full.Width - textPaint.MeasureText(sacText)) / 2,
         *              full.Height - 50, textPaint);
         *      }
         *
         *      return full;
         *  }
         * }*/

        public Dictionary <Section, BitmapData> GenerateSections(Dictionary <StorefrontEntry, BitmapData> entries)
        {
            int maxEntriesPerRow = 6;

            Dictionary <Section, BitmapData> sectionsBitmaps = new Dictionary <Section, BitmapData>();

            var content = FortniteContent.Get();

            List <Section> sections = new List <Section>();

            entries.Keys.ToList().ForEach(key =>
            {
                if (!sections.Contains(x => x.SectionId == key.SectionId))
                {
                    if (content.ShopSections.Contains(key.SectionId))
                    {
                        sections.Add(content.ShopSections.Get(key.SectionId));
                    }
                    else
                    {
                        sections.Add(new Section
                        {
                            SectionId       = key.SectionId,
                            DisplayName     = "",
                            LandingPriority = 49
                        });
                    }
                }
            });

            List <int> entriesCount = new List <int>();

            sections.ForEach(section =>
            {
                int count = 0;

                entries.ToList().ForEach(entry =>
                {
                    if (entry.Key.SectionId == section.SectionId)
                    {
                        count++;
                    }
                });

                entriesCount.Add(count);
            });

            maxEntriesPerRow = Math.Clamp(entriesCount.Max(), 0, maxEntriesPerRow);

            int th = (int)(ChicRatios.Get1024(200) * EntryHeight);
            int hf = (int)(ChicRatios.Get1024(150) * EntryHeight);
            int h  = (int)(ChicRatios.Get1024(100) * EntryHeight);
            int f  = (int)(ChicRatios.Get1024(50) * EntryHeight);

            foreach (var section in sections)
            {
                Dictionary <StorefrontEntry, BitmapData> se = new Dictionary <StorefrontEntry, BitmapData>();

                entries.ToList().ForEach(entry =>
                {
                    if (entry.Key.SectionId == section.SectionId)
                    {
                        se.Add(entry);
                    }
                });

                Dictionary <StorefrontEntry, BitmapData> sectionEntries = new Dictionary <StorefrontEntry, BitmapData>();
                sectionEntries.Add(se.ToList().Sort(EntryComparer.Comparer, 0));

                int extraHeight = section.HasName ? th : 0;

                SKBitmap bitmap = new SKBitmap(h /*150*/ + maxEntriesPerRow * (EntryWidth + h /*+ 50*/), extraHeight + (int)Math.Ceiling((decimal)sectionEntries.Count / maxEntriesPerRow) * (EntryHeight + h /*+ 50*/));

                using (SKCanvas c = new SKCanvas(bitmap))
                {
                    using (var paint = new SKPaint
                    {
                        IsAntialias = true,
                        FilterQuality = SKFilterQuality.High,
                        Color = SKColor.Parse("#e7accb")//new SKColor(40, 40, 40)
                    }) c.DrawRect(0, 0, bitmap.Width, bitmap.Height, paint);

                    int x      = f;//100;
                    int y      = extraHeight;
                    int row    = 0;
                    int column = 0;

                    for (int i = 0; i < sectionEntries.Count; i++)
                    {
                        var entry = sectionEntries.ToList()[i];

                        using (var b = LoadFromCache(entry.Value))
                        {
                            using (var paint = new SKPaint {
                                IsAntialias = true, FilterQuality = SKFilterQuality.High
                            })
                                c.DrawBitmap(b, x, y, paint);
                        }

                        GC.Collect();

                        if (++column == maxEntriesPerRow)
                        {
                            row++;
                            column = 0;
                            //x = 50;//100;
                        }

                        x = f + (EntryWidth + h) * column; /*+ 50*/
                        y = extraHeight + (EntryHeight + h /*+ 50*/) * row;
                    }

                    using (var paint = new SKPaint
                    {
                        IsAntialias = true,
                        FilterQuality = SKFilterQuality.High,
                        Color = SKColors.White,
                        TextSize = h,
                        Typeface = ChicTypefaces.BurbankBigRegularBlack,
                        TextAlign = SKTextAlign.Left,
                        ImageFilter = SKImageFilter.CreateDropShadow(0, 0, 10, 10, SKColors.Black)
                    }) if (section.HasName)
                        {
                            c.DrawText(section.DisplayName, h, hf, paint);
                        }
                }

                sectionEntries = null;

                sectionsBitmaps.Add(section, SaveToCache(bitmap, "section_" + section.SectionId));
            }

            content  = null;
            sections = null;
            entries  = null;

            GC.Collect();

            return(sectionsBitmaps);
        }
Пример #13
0
        public List <BitmapData> DrawSections(ShopV2 shop)
        {
            int maxEntriesPerRow = 6;
            var result           = new List <BitmapData>();

            maxEntriesPerRow = Math.Clamp(shop.Sections.Max(x => x.Value.Count), 0, maxEntriesPerRow);

            int th = (int)(ChicRatios.Get1024(200) * EntryHeight);
            int hf = (int)(ChicRatios.Get1024(150) * EntryHeight);
            int h  = (int)(ChicRatios.Get1024(100) * EntryHeight);
            int f  = (int)(ChicRatios.Get1024(50) * EntryHeight);

            int width = h + maxEntriesPerRow * (EntryWidth + h);

            foreach (var section in shop.Sections)
            {
                var sectionInfo = shop.SectionInfos.Find(x => x.SectionId == section.Key);
                int extraHeight = sectionInfo.HasName ? th : 0;
                int height      = extraHeight + (int)Math.Ceiling((decimal)section.Value.Count / maxEntriesPerRow) * (EntryHeight + h);

                using (SKBitmap bitmap = new SKBitmap(width, height))
                {
                    using (SKCanvas c = new SKCanvas(bitmap))
                    {
                        using (var paint = new SKPaint
                        {
                            IsAntialias = true,
                            FilterQuality = SKFilterQuality.High,
                            Color = SKColor.Parse("#e7accb")//new SKColor(40, 40, 40)
                        }) c.DrawRect(0, 0, width, height, paint);

                        int x      = f;//100;
                        int y      = extraHeight;
                        int row    = 0;
                        int column = 0;

                        for (int i = 0; i < section.Value.Count; i++)
                        {
                            var entry = section.Value[i];

                            using (var b = DrawEntry(entry) /*LoadFromCache(entry.CacheId)*/)
                            {
                                using (var paint = new SKPaint {
                                    IsAntialias = true, FilterQuality = SKFilterQuality.High
                                })
                                    c.DrawBitmap(b, x, y, paint);
                            }

                            GC.Collect();

                            if (++column == maxEntriesPerRow)
                            {
                                row++;
                                column = 0;
                                //x = 50;//100;
                            }

                            x = f + (EntryWidth + h) * column; /*+ 50*/
                            y = extraHeight + (EntryHeight + h /*+ 50*/) * row;
                        }

                        using (var paint = new SKPaint
                        {
                            IsAntialias = true,
                            FilterQuality = SKFilterQuality.High,
                            Color = SKColors.White,
                            TextSize = h,
                            Typeface = ChicTypefaces.BurbankBigRegularBlack,
                            TextAlign = SKTextAlign.Left,
                            ImageFilter = SKImageFilter.CreateDropShadow(0, 0, 10, 10, SKColors.Black)
                        }) if (sectionInfo.HasName)
                            {
                                c.DrawText(sectionInfo.DisplayName, h, hf, paint);
                            }
                    }

                    result.Add(SaveToCache(bitmap, section.Key));
                }
            }

            return(result);
        }
Пример #14
0
        /// <summary>
        /// 创建验证码的图片
        /// </summary>
        public byte[] CreateValidationCodeGraphic()
        {
            Random rand = new Random(Guid.NewGuid().GetHashCode());

            var randAngle = 40;
            var mapWidth  = ValidationCode.Length * 18;
            var mapHeight = 28;

            using (var bitmap = new SKBitmap(mapWidth, mapHeight))
            {
                using (var canvas = new SKCanvas(bitmap))
                {
                    canvas.Clear(SKColors.AliceBlue);

                    var paint = new SKPaint()
                    {
                        Color = SKColors.LightGray,
                    };
                    for (int i = 0; i < 50; i++)
                    {
                        int x = rand.Next(0, bitmap.Width);
                        int y = rand.Next(0, bitmap.Height);

                        canvas.DrawRect(new SKRect(x, y, x + 1, y + 1), paint);
                    }

                    var      chars  = ValidationCode.ToCharArray();
                    var      colors = new[] { SKColors.Black, SKColors.Red, SKColors.DarkBlue, SKColors.Green, SKColors.Orange, SKColors.Brown, SKColors.DarkCyan, SKColors.Purple };
                    string[] font   = { "Verdana", "Microsoft Sans Serif", "Comic Sans MS", "Arial" };

                    canvas.Translate(-4, 0);

                    for (int i = 0; i < chars.Length; i++)
                    {
                        int colorIndex = rand.Next(7);
                        int fontIndex  = rand.Next(5);

                        var   fontColor = colors[colorIndex];
                        var   foneSize  = rand.Next(18, 25);
                        float angle     = rand.Next(-randAngle, randAngle);

                        SKPoint point = new SKPoint(16, 28 / 2 + 4);

                        canvas.Translate(point);
                        canvas.RotateDegrees(angle);

                        var textPaint = new SKPaint()
                        {
                            TextAlign      = SKTextAlign.Center,
                            Color          = fontColor,
                            TextSize       = foneSize,
                            IsVerticalText = true,
                            IsAntialias    = true,

                            //IsAntialias = rand.Next(1) == 1 ? true : false,
                            //FakeBoldText = true,
                            //FilterQuality = SKFilterQuality.High,
                            //HintingLevel = SKPaintHinting.Full,

                            //IsEmbeddedBitmapText = true,
                            //LcdRenderText = true,
                            //Style = SKPaintStyle.StrokeAndFill,
                            //TextEncoding = SKTextEncoding.Utf8,
                        };

                        canvas.DrawText(chars[i].ToString(), new SKPoint(0, 0), textPaint);
                        canvas.RotateDegrees(-angle);
                        canvas.Translate(0, -point.Y);
                    }

                    using (var image = SKImage.FromBitmap(bitmap))
                    {
                        using (var ms = new MemoryStream())
                        {
                            image.Encode(SKEncodedImageFormat.Png, 90).SaveTo(ms);
                            return(ms.ToArray());
                        }
                    }
                }
            }
        }
Пример #15
0
        public void RenderChart()
        {
            canvas.Clear(SKColors.White);

            // set up drawing tools
            using (var paint = new SKPaint())
            {
                paint.IsAntialias = true;
                paint.Color       = new SKColor(0x2c, 0x3e, 0x50);
                paint.StrokeCap   = SKStrokeCap.Round;

                var xCoordStart = new Point(0 + (width / 20), height - (height / 3));
                var xCoordEnd   = new Point(width - (width / 20), height - (height / 3));

                var yCoordStart = new Point(0 + (width / 20), height - (height / 3));
                var yCoordEnd   = new Point(0 + (width / 20), 0 + (height / 95));

                var zCoordStart = new Point(width - (width / 20), xCoordStart.Y - 150);
                var zCoordEnd   = new Point(width - (width / 20), xCoordStart.Y + 150);

                canvas.DrawLine(xCoordStart.X, xCoordStart.Y, xCoordEnd.X, xCoordEnd.Y, new SKPaint());
                canvas.DrawLine(yCoordStart.X, yCoordStart.Y, yCoordEnd.X, yCoordEnd.Y, new SKPaint());
                canvas.DrawLine(zCoordStart.X, zCoordStart.Y, zCoordEnd.X, zCoordEnd.Y, new SKPaint());

                //TODO: temporary workaround ;)
                canvas.DrawLine(zCoordStart.X, zCoordStart.Y - 200, zCoordEnd.X, zCoordEnd.Y, new SKPaint());
                //assume: data to x and y coord are ordered

                //map xcoord between xstart and xend;
                var xRange    = xCoordEnd.X - xCoordStart.X;
                var xPlotUnit = xRange / DatesList.Count;

                //map ycoord between ystart and yend
                var yRange    = yCoordStart.Y - yCoordEnd.Y;
                var yPlotUnit = yRange / (float)(Values.Select(n => n.Item1).Max() - Values.Select(n => n.Item1).Min());

                //map zcoord between zstart and zend
                var zRange    = zCoordStart.Y - zCoordEnd.Y;
                var zPlotUnit = zRange / (float)(Gains.Max() - Gains.Min());

                var maxGains = GainsList.Max();
                var minGains = GainsList.Min();
                //Plot the values
                for (int i = 0; i < DatesList.Count; i++)
                {
                    var xCoord = xCoordStart.X + (i * xPlotUnit);
                    var yCoord = yCoordStart.Y - (yPlotUnit * (float)(ValuesList[i].Item1 - Values.Select(n => n.Item1).Min()));
                    //canvas.DrawPoint(xCoord,yCoord, new SKPaint());

                    var skPaint = new SKPaint();

                    switch (ValuesList[i].Item2)
                    {
                    case PointColor.Green:
                        skPaint.Color = new SKColor(0, 255, 0);
                        break;

                    case PointColor.Red:
                        skPaint.Color = new SKColor(255, 0, 0);
                        break;

                    default:
                        break;
                    }

                    canvas.DrawCircle(xCoord, yCoord, 1, skPaint);

                    var gainyCoord = zCoordEnd.Y - 150 + (zPlotUnit * (float)(GainsList[i]));

                    if (GainsList[i] == maxGains || GainsList[i] == minGains)
                    {
                        canvas.DrawLine(zCoordEnd.X - 5, gainyCoord, zCoordEnd.X + 5, gainyCoord, new SKPaint());

                        var plusSign = GainsList[i] > 0 ? "+" : String.Empty;
                        canvas.DrawText(plusSign + (int)GainsList[i] + "%", zCoordEnd.X + 8, gainyCoord + 5, new SKPaint());
                    }

                    canvas.DrawCircle(xCoord, gainyCoord, 1, new SKPaint());
                }

                canvas.DrawText("0%", zCoordEnd.X + 8, zCoordEnd.Y - 153, new SKPaint());

                //add x labels
                var nOfXLabels     = 8;
                var xLabelPlotUnit = xRange / (nOfXLabels - 1);


                for (int i = 0; i < (nOfXLabels - 1); i++)
                {
                    canvas.DrawLine(xCoordStart.X + (xLabelPlotUnit * i),
                                    yCoordStart.Y - 5, xCoordStart.X + (xLabelPlotUnit * i), yCoordStart.Y + 5,
                                    new SKPaint());

                    var txt = DatesList[(i) * DatesList.Count() / (nOfXLabels - 1)].ToShortDateString();
                    canvas.DrawText(txt, xCoordStart.X + (xLabelPlotUnit * i) - 35,
                                    yCoordStart.Y + 25, new SKPaint());
                }
                canvas.DrawLine(xCoordEnd.X,
                                yCoordStart.Y - 5, xCoordEnd.X, yCoordStart.Y + 5,
                                new SKPaint());
                canvas.DrawText(Dates.Last().ToShortDateString(), xCoordEnd.X - 35,
                                yCoordStart.Y + 25, new SKPaint());


                //add y labels
                var nOfYLabels     = 8;
                var yLabelPlotUnit = yRange / (nOfYLabels - 1);

                var vv  = (float)(Values.Select(n => n.Item1).Max() - Values.Select(n => n.Item1).Min());
                var vv2 = vv / (nOfYLabels - 1);
                for (int i = 0; i < (nOfYLabels - 1); i++)
                {
                    canvas.DrawLine(yCoordStart.X - 5, yCoordStart.Y - (yLabelPlotUnit * i),
                                    yCoordStart.X + 5, yCoordStart.Y - (yLabelPlotUnit * i), new SKPaint());


                    var val = Values.Select(n => n.Item1).Min() + (Decimal)i * (decimal)vv2;
                    canvas.DrawText(((int)val).ToString(), yCoordStart.X - 38,
                                    yCoordStart.Y - (yLabelPlotUnit * i) + 5, new SKPaint());
                }

                canvas.DrawLine(yCoordStart.X - 5, yCoordEnd.Y - 1,
                                yCoordStart.X + 5, yCoordEnd.Y - 1, new SKPaint());

                canvas.DrawText(((int)Values.Select(n => n.Item1).Max()).ToString(), yCoordStart.X - 38,
                                yCoordEnd.Y + 5, new SKPaint());


                //Add z. label (gains)
            }
        }
Пример #16
0
        public async Task drawGaugeAsync()
        {
            // Radial Gauge Constants
            int uPadding         = 150;
            int side             = 500;
            int radialGaugeWidth = 25;

            // Line TextSize inside Radial Gauge
            int lineSize1 = 220;
            int lineSize2 = 70;
            int lineSize3 = 80;

            // Line Y Coordinate inside Radial Gauge
            int lineHeight1 = 100;
            int lineHeight2 = 200;
            int lineHeight3 = 300;

            // Start & End Angle for Radial Gauge
            float startAngle = -220;
            float sweepAngle = 260;

            try
            {
                // Getting Canvas Info
                SKImageInfo info    = args.Info;
                SKSurface   surface = args.Surface;
                SKCanvas    canvas  = surface.Canvas;
                progressUtils.setDevice(info.Height, info.Width);
                canvas.Clear();

                // Getting Device Specific Screen Values
                // -------------------------------------------------

                // Top Padding for Radial Gauge
                float upperPading = progressUtils.getFactoredHeight(uPadding);

                /* Coordinate Plotting for Radial Gauge
                 *
                 *    (X1,Y1) ------------
                 *           |   (XC,YC)  |
                 *           |      .     |
                 *         Y |            |
                 *           |            |
                 *            ------------ (X2,Y2))
                 *                  X
                 *
                 * To fit a perfect Circle inside --> X==Y
                 *       i.e It should be a Square
                 */

                // Xc & Yc are center of the Circle
                int   Xc = info.Width / 2;
                float Yc = progressUtils.getFactoredHeight(side);

                // X1 Y1 are lefttop cordiates of rectange
                int X1 = (int)(Xc - Yc);
                int Y1 = (int)(Yc - Yc + upperPading);

                // X2 Y2 are rightbottom cordiates of rectange
                int X2 = (int)(Xc + Yc);
                int Y2 = (int)(Yc + Yc + upperPading);

                //Loggig Screen Specific Calculated Values
                Debug.WriteLine("INFO " + info.Width + " - " + info.Height);
                Debug.WriteLine(" C : " + upperPading + "  " + info.Height);
                Debug.WriteLine(" C : " + Xc + "  " + Yc);
                Debug.WriteLine("XY : " + X1 + "  " + Y1);
                Debug.WriteLine("XY : " + X2 + "  " + Y2);

                //  Empty Gauge Styling
                SKPaint paint1 = new SKPaint
                {
                    Style       = SKPaintStyle.Stroke,
                    Color       = Color.FromHex("#e0dfdf").ToSKColor(),             // Colour of Radial Gauge
                    StrokeWidth = progressUtils.getFactoredWidth(radialGaugeWidth), // Width of Radial Gauge
                    StrokeCap   = SKStrokeCap.Round                                 // Round Corners for Radial Gauge
                };

                // Filled Gauge Styling
                SKPaint paint2 = new SKPaint
                {
                    Style       = SKPaintStyle.Stroke,
                    Color       = Color.FromHex("#05c782").ToSKColor(),             // Overlay Colour of Radial Gauge
                    StrokeWidth = progressUtils.getFactoredWidth(radialGaugeWidth), // Overlay Width of Radial Gauge
                    StrokeCap   = SKStrokeCap.Round                                 // Round Corners for Radial Gauge
                };

                // Defining boundaries for Gauge
                SKRect rect = new SKRect(X1, Y1, X2, Y2);


                //canvas.DrawRect(rect, paint1);
                //canvas.DrawOval(rect, paint1);

                // Rendering Empty Gauge
                SKPath path1 = new SKPath();
                path1.AddArc(rect, startAngle, sweepAngle);
                canvas.DrawPath(path1, paint1);

                // Rendering Filled Gauge
                SKPath path2 = new SKPath();
                path2.AddArc(rect, startAngle, (float)sweepAngleSlider.Value);
                canvas.DrawPath(path2, paint2);

                //---------------- Drawing Text Over Gauge ---------------------------

                // Achieved Minutes
                using (SKPaint skPaint = new SKPaint())
                {
                    skPaint.Style       = SKPaintStyle.Fill;
                    skPaint.IsAntialias = true;
                    skPaint.Color       = SKColor.Parse("#676a69");
                    skPaint.TextAlign   = SKTextAlign.Center;
                    skPaint.TextSize    = progressUtils.getFactoredHeight(lineSize1);
                    skPaint.Typeface    = SKTypeface.FromFamilyName(
                        "Arial",
                        SKFontStyleWeight.Bold,
                        SKFontStyleWidth.Normal,
                        SKFontStyleSlant.Upright);

                    // Drawing Achieved Minutes Over Radial Gauge
                    if (sw_listToggle.IsToggled)
                    {
                        canvas.DrawText(monthlyWorkout + "", Xc, Yc + progressUtils.getFactoredHeight(lineHeight1), skPaint);
                    }
                    else
                    {
                        canvas.DrawText(dailyWorkout + "", Xc, Yc + progressUtils.getFactoredHeight(lineHeight1), skPaint);
                    }
                }

                // Achieved Minutes Text Styling
                using (SKPaint skPaint = new SKPaint())
                {
                    skPaint.Style       = SKPaintStyle.Fill;
                    skPaint.IsAntialias = true;
                    skPaint.Color       = SKColor.Parse("#676a69");
                    skPaint.TextAlign   = SKTextAlign.Center;
                    skPaint.TextSize    = progressUtils.getFactoredHeight(lineSize2);
                    canvas.DrawText("Minutes", Xc, Yc + progressUtils.getFactoredHeight(lineHeight2), skPaint);
                }

                // Goal Minutes Text Styling
                using (SKPaint skPaint = new SKPaint())
                {
                    skPaint.Style       = SKPaintStyle.Fill;
                    skPaint.IsAntialias = true;
                    skPaint.Color       = SKColor.Parse("#e2797a");
                    skPaint.TextAlign   = SKTextAlign.Center;
                    skPaint.TextSize    = progressUtils.getFactoredHeight(lineSize3);

                    // Drawing Text Over Radial Gauge
                    if (sw_listToggle.IsToggled)
                    {
                        canvas.DrawText("Goal " + goal + " Min", Xc, Yc + progressUtils.getFactoredHeight(lineHeight3), skPaint);
                    }
                    else
                    {
                        canvas.DrawText("Goal " + goal / 30 + " Min", Xc, Yc + progressUtils.getFactoredHeight(lineHeight3), skPaint);
                    }
                }
            }
            catch (Exception e)
            {
                Debug.WriteLine(e.StackTrace);
            }
        }
    public static void DrawXamagon(SKBitmap bitmap)
    {
        var canvas = new SKCanvas(bitmap);

        // flip the texture due to coordinate differences
        canvas.Scale(1, -1, 0, bitmap.Height / 2f);

        // white background
        canvas.Clear(SKColors.White);

        // blue
        var bluePaint = new SKPaint
        {
            StrokeCap   = SKStrokeCap.Round,
            StrokeJoin  = SKStrokeJoin.Round,
            StrokeWidth = 30,
            Color       = (SKColor)0xff3498db,
            Style       = SKPaintStyle.StrokeAndFill,
            IsAntialias = true
        };
        // xamagon path
        var xamagon = new SKPath();

        xamagon.MoveTo(40, 80);
        xamagon.LineTo(70, 25);
        xamagon.LineTo(135, 25);
        xamagon.LineTo(166, 80);
        xamagon.LineTo(135, 135);
        xamagon.LineTo(70, 135);
        xamagon.Close();
        // draw blue xamagon
        canvas.DrawPath(xamagon, bluePaint);

        // white
        var whitePaint = new SKPaint
        {
            StrokeCap   = SKStrokeCap.Round,
            StrokeJoin  = SKStrokeJoin.Round,
            StrokeWidth = 15,
            Color       = SKColors.White,
            Style       = SKPaintStyle.Stroke,
            IsAntialias = true
        };
        // the X path
        var x = new SKPath();

        x.MoveTo(80, 110);
        x.LineTo(95, 80);
        x.LineTo(80, 50);
        x.MoveTo(125, 110);
        x.LineTo(110, 80);
        x.LineTo(125, 50);
        // draw white X
        canvas.DrawPath(x, whitePaint);

        // green
        var greenPaint = new SKPaint
        {
            Typeface    = SKTypeface.FromFamilyName(null, SKTypefaceStyle.Bold),
            TextAlign   = SKTextAlign.Center,
            TextSize    = 30,
            Color       = (SKColor)0xff77d065,
            Style       = SKPaintStyle.Fill,
            IsAntialias = true
        };

        // draw green text
        canvas.DrawText("Skia-Demo", 100, 180, greenPaint);

        // push to the pixel buffer
        canvas.Flush();
    }
Пример #18
0
            private bool DrawOntoCanvas(IntPtr handle, SKCanvas Canvas, bool forcerender = false)
            {
                var hwnd = Hwnd.ObjectFromHandle(handle);

                var x        = 0;
                var y        = 0;
                var wasdrawn = false;

                XplatUI.driver.ClientToScreen(hwnd.client_window, ref x, ref y);

                var width         = 0;
                var height        = 0;
                var client_width  = 0;
                var client_height = 0;


                if (hwnd.hwndbmp != null && hwnd.Mapped && hwnd.Visible && !hwnd.zombie)
                {
                    // setup clip
                    var parent = hwnd;
                    Canvas.ClipRect(
                        SKRect.Create(0, 0, Screen.PrimaryScreen.Bounds.Width * 2,
                                      Screen.PrimaryScreen.Bounds.Height * 2), (SKClipOperation)5);

                    while (parent != null)
                    {
                        var xp = 0;
                        var yp = 0;
                        XplatUI.driver.ClientToScreen(parent.client_window, ref xp, ref yp);

                        Canvas.ClipRect(SKRect.Create(xp, yp, parent.Width, parent.Height),
                                        SKClipOperation.Intersect);

                        parent = parent.parent;
                    }

                    Monitor.Enter(XplatUIMine.paintlock);

                    if (hwnd.ClientWindow != hwnd.WholeWindow)
                    {
                        var ctl = Control.FromHandle(hwnd.ClientWindow);
                        var frm = ctl as Form;

                        Hwnd.Borders borders = new Hwnd.Borders();

                        if (frm != null)
                        {
                            borders = Hwnd.GetBorders(frm.GetCreateParams(), null);

                            Canvas.ClipRect(
                                SKRect.Create(0, 0, Screen.PrimaryScreen.Bounds.Width * 2,
                                              Screen.PrimaryScreen.Bounds.Height * 2), (SKClipOperation)5);
                        }

                        if (Canvas.DeviceClipBounds.Width > 0 &&
                            Canvas.DeviceClipBounds.Height > 0)
                        {
                            if (hwnd.DrawNeeded || forcerender)
                            {
                                if (hwnd.hwndbmpNC != null)
                                {
                                    Canvas.DrawImage(hwnd.hwndbmpNC,
                                                     new SKPoint(x - borders.left, y - borders.top), new SKPaint()
                                    {
                                        ColorFilter =
                                            SKColorFilter.CreateColorMatrix(new float[]
                                        {
                                            0.75f, 0.25f, 0.025f, 0, 0,
                                            0.25f, 0.75f, 0.25f, 0, 0,
                                            0.25f, 0.25f, 0.75f, 0, 0,
                                            0, 0, 0, 1, 0
                                        })
                                    });
                                }

                                Canvas.ClipRect(
                                    SKRect.Create(x, y, hwnd.width - borders.right - borders.left,
                                                  hwnd.height - borders.top - borders.bottom), SKClipOperation.Intersect);

                                Canvas.DrawDrawable(hwnd.hwndbmp,
                                                    new SKPoint(x, y));

                                wasdrawn = true;
                            }

                            hwnd.DrawNeeded = false;
                        }
                        else
                        {
                            Monitor.Exit(XplatUIMine.paintlock);
                            return(true);
                        }
                    }
                    else
                    {
                        if (Canvas.DeviceClipBounds.Width > 0 &&
                            Canvas.DeviceClipBounds.Height > 0)
                        {
                            if (hwnd.DrawNeeded || forcerender)
                            {
                                Canvas.DrawDrawable(hwnd.hwndbmp,
                                                    new SKPoint(x + 0, y + 0));

                                wasdrawn = true;
                            }

                            hwnd.DrawNeeded = false;

/*
 *                      surface.Canvas.DrawText(Control.FromHandle(hwnd.ClientWindow).Name,
 *                          new SKPoint(x, y + 15),
 *                          new SKPaint() {Color = SKColor.Parse("55ffff00")});
 *                      /*surface.Canvas.DrawText(hwnd.ClientWindow.ToString(), new SKPoint(x,y+15),
 *                          new SKPaint() {Color = SKColor.Parse("ffff00")});*/
                        }
                        else
                        {
                            Monitor.Exit(XplatUIMine.paintlock);
                            return(true);
                        }
                    }

                    Monitor.Exit(XplatUIMine.paintlock);
                }

                var ctrl = Control.FromHandle(hwnd.ClientWindow);

                Canvas.DrawText(x + " " + y + " " + ctrl.Name + " " + hwnd.width + " " + hwnd.Height, x, y + 10, new SKPaint()
                {
                    Color = SKColors.Red
                });

                if (hwnd.Mapped && hwnd.Visible)
                {
                    IEnumerable <Hwnd> children;
                    lock (Hwnd.windows)
                        children = Hwnd.windows.OfType <System.Collections.DictionaryEntry>()
                                   .Where(hwnd2 =>
                        {
                            var Key   = (IntPtr)hwnd2.Key;
                            var Value = (Hwnd)hwnd2.Value;
                            if (Value.ClientWindow == Key && Value.Parent == hwnd && Value.Visible &&
                                Value.Mapped && !Value.zombie)
                            {
                                return(true);
                            }
                            return(false);
                        }).Select(a => (Hwnd)a.Value).ToArray();

                    children = children.OrderBy((hwnd2) =>
                    {
                        var info = XplatUIMine.GetInstance().GetZOrder(hwnd2.client_window);
                        if (info.top)
                        {
                            return(1000);
                        }
                        if (info.bottom)
                        {
                            return(0);
                        }
                        return(500);
                    });

                    foreach (var child in children)
                    {
                        DrawOntoCanvas(child.ClientWindow, Canvas, true);
                    }
                }

                return(true);
            }
Пример #19
0
        public void DrawNode(SKCanvas ctx, ComlinkNode node, bool selected)
        {
            using var headerTextPaint = _paint.Clone().WithColor(0xFF_FFFFFF).WithTypeface(_headerTypeface);
            using var textPaint       = _paint.Clone().WithColor(0xFF_FFFFFF).WithTypeface(_nodeTypeface);

            var headerLineHeight     = (int)(headerTextPaint.FontMetrics.Descent - headerTextPaint.FontMetrics.Ascent + headerTextPaint.FontMetrics.Leading);
            var headerBaselineOffset = (int)-headerTextPaint.FontMetrics.Ascent;

            var lineHeight = (int)(textPaint.FontMetrics.Descent - textPaint.FontMetrics.Ascent + textPaint.FontMetrics.Leading);

            var width   = GetNodeWidth(node, headerTextPaint, textPaint);
            var numPins = Math.Max(node.InputPins.Count, node.OutputPins.Count);
            var height  = lineHeight * (numPins - 1) - textPaint.FontMetrics.Ascent + textPaint.FontMetrics.Descent + 6;

            var x = node.X;
            var y = node.Y;

            var headerX      = x - NodeBorderSize;
            var headerY      = y - headerLineHeight;
            var headerWidth  = width + 2 * NodeBorderSize;
            var headerHeight = height + headerLineHeight + NodeBorderSize;

            if (selected)
            {
                var selectionStrokeSize = NodeBorderSize / 2f;

                using var paint   = _paint.Clone();
                using var path    = SKPathEffect.CreateDash(SelectionStrokeInterval, (float)((DateTime.Now - DateTime.Today).TotalSeconds * 10 % 20));
                paint.IsStroke    = true;
                paint.Color       = new SKColor(SelectionBorderColor);
                paint.StrokeWidth = selectionStrokeSize;
                paint.PathEffect  = path;

                ctx.DrawRoundRect(headerX - selectionStrokeSize, headerY - selectionStrokeSize, headerWidth + 2 * selectionStrokeSize, headerHeight + 2 * selectionStrokeSize,
                                  NodeCornerRadius + selectionStrokeSize, NodeCornerRadius + selectionStrokeSize, paint);
            }

            // header
            ctx.DrawRoundRect(headerX, headerY, headerWidth, headerHeight, NodeCornerRadius, NodeCornerRadius, _paint.WithColor(node.Color));

            // title
            ctx.DrawCircle(x + (headerBaselineOffset - NodeBorderSize + 1) / 2f, y - headerLineHeight / 2f, headerLineHeight / 4f, headerTextPaint);
            ctx.DrawText(node.Name, x + headerBaselineOffset, y - headerLineHeight + headerBaselineOffset, headerTextPaint);

            // body
            ctx.DrawRoundRect(x, y, width, height, NodeCornerRadius - NodeBorderSize + 1, NodeCornerRadius - NodeBorderSize + 1, _paint.WithColor(BodyColor));

            y -= (int)(textPaint.FontMetrics.Ascent - 3);

            var triangleRadius = lineHeight / 10f;
            var circleRadius   = lineHeight / 3f;
            var pinOffset      = lineHeight / 4f;

            var pY = y;

            for (var i = 0; i < node.InputPins.Count; i++, pY += lineHeight)
            {
                var pin = node.InputPins[i];

                if (pin is FlowInputPin)
                {
                    ctx.DrawRoundedTriangle(x - pinOffset / 2, pY - pinOffset, pinOffset, triangleRadius + NodeBorderSize, _paint.WithColor(BodyColor));
                    ctx.DrawRoundedTriangle(x - pinOffset / 2, pY - pinOffset, pinOffset, triangleRadius, _paint.WithColor(pin.Color));
                }
                else
                {
                    // input dot
                    ctx.DrawCircle(x, pY - pinOffset, circleRadius, _paint.WithColor(BodyColor));
                    ctx.DrawCircle(x, pY - pinOffset, circleRadius - NodeBorderSize, _paint.WithColor(pin.Color));
                }

                ctx.DrawText(pin.Name, x + lineHeight / 2f, pY, textPaint);
            }

            pY = y;
            for (var i = 0; i < node.OutputPins.Count; i++, pY += lineHeight)
            {
                var pin = node.OutputPins[i];

                if (pin is FlowOutputPin)
                {
                    ctx.DrawRoundedTriangle(x + width - pinOffset / 2, pY - pinOffset, pinOffset, triangleRadius + NodeBorderSize, _paint.WithColor(BodyColor));
                    ctx.DrawRoundedTriangle(x + width - pinOffset / 2, pY - pinOffset, pinOffset, triangleRadius, _paint.WithColor(pin.Color));
                }
                else
                {
                    // output dot
                    ctx.DrawCircle(x + width, pY - pinOffset, circleRadius, _paint.WithColor(BodyColor));
                    ctx.DrawCircle(x + width, pY - pinOffset, circleRadius - 3, _paint.WithColor(pin.Color));
                }

                var textWidth = textPaint.MeasureText(pin.Name);
                ctx.DrawText(pin.Name, x + width - textWidth - lineHeight / 2f, pY, textPaint);
            }
        }
Пример #20
0
        public virtual void OnPaint(SKCanvas canvas)
        {
            var owner = OwnerControl;

            if (owner is Menu menu)
            {
                // Background
                var background_color = Hovered || IsDropDownOpened ? Theme.RibbonItemHighlightColor : Theme.NeutralGray;
                canvas.FillRectangle(Bounds, background_color);

                // Text
                var font_color = Theme.DarkTextColor;
                var font_size  = menu.LogicalToDeviceUnits(Theme.FontSize);

                canvas.DrawText(Text, Theme.UIFont, font_size, Bounds, font_color, ContentAlignment.MiddleCenter);

                return;
            }

            if (owner is ToolBar bar)
            {
                // Background
                var background_color = Hovered || IsDropDownOpened ? Theme.RibbonItemHighlightColor : Theme.NeutralGray;
                canvas.FillRectangle(Bounds, background_color);

                var bounds = Bounds;
                bounds.X += bar.LogicalToDeviceUnits(8);

                // Image
                if (Image != null)
                {
                    var image_size   = bar.LogicalToDeviceUnits(20);
                    var image_bounds = DrawingExtensions.CenterSquare(Bounds, image_size);
                    var image_rect   = new Rectangle(bounds.Left, image_bounds.Top, image_size, image_size);
                    canvas.DrawBitmap(Image, image_rect);

                    bounds.X += bar.LogicalToDeviceUnits(28);
                }
                else
                {
                    bounds.X += bar.LogicalToDeviceUnits(4);
                }

                // Text
                var font_color = Theme.DarkTextColor;
                var font_size  = bar.LogicalToDeviceUnits(Theme.FontSize);

                bounds.Y += 1;
                canvas.DrawText(Text, Theme.UIFont, font_size, bounds, font_color, ContentAlignment.MiddleLeft);
                bounds.Y -= 1;

                // Dropdown Arrow
                if (HasItems)
                {
                    var arrow_bounds = DrawingExtensions.CenterSquare(Bounds, 16);
                    var arrow_area   = new Rectangle(Bounds.Right - 20, arrow_bounds.Top, 16, 16);
                    ControlPaint.DrawArrowGlyph(new PaintEventArgs(SKImageInfo.Empty, canvas, bar.Scaling), arrow_area, Theme.DarkTextColor, ArrowDirection.Down);
                }

                return;
            }

            if (owner is MenuDropDown dropdown)
            {
                // Background
                var background_color = Hovered || IsDropDownOpened ? Theme.RibbonItemHighlightColor : Theme.LightTextColor;
                canvas.FillRectangle(Bounds, background_color);

                // Image
                if (Image != null)
                {
                    var image_bounds = DrawingExtensions.CenterSquare(Bounds, 16);
                    var image_rect   = new Rectangle(Bounds.Left + 6, image_bounds.Top, 16, 16);
                    canvas.DrawBitmap(Image, image_rect);
                }

                // Text
                var font_color = Theme.DarkTextColor;
                var font_size  = dropdown.LogicalToDeviceUnits(Theme.FontSize);
                var bounds     = Bounds;
                bounds.X += 28;
                canvas.DrawText(Text, Theme.UIFont, font_size, bounds, font_color, ContentAlignment.MiddleLeft);

                // Dropdown Arrow
                if (HasItems)
                {
                    var arrow_bounds = DrawingExtensions.CenterSquare(Bounds, 16);
                    var arrow_area   = new Rectangle(Bounds.Right - 20, arrow_bounds.Top, 16, 16);
                    ControlPaint.DrawArrowGlyph(new PaintEventArgs(SKImageInfo.Empty, canvas, dropdown.Scaling), arrow_area, Theme.DarkTextColor, ArrowDirection.Right);
                }

                return;
            }
        }
Пример #21
0
        public void UpdateMeter(double velocity, SKImageInfo info, SKSurface surface)
        {
            SKCanvas canvas = surface.Canvas;

            canvas.Clear();

            int drawResolution = info.Height > info.Width ? info.Width : info.Height;
            int rectResolution = drawResolution - 2 * MinMeterMargin;


            //SKRect rect = new SKRect((info.Width - resolution) / 2, (info.Height - resolution) / 2, resolution, resolution);
            SKRect rect = new SKRect((info.Width - rectResolution) / 2,
                                     (info.Height - rectResolution) / 2,
                                     ((info.Width - rectResolution) / 2) + rectResolution,
                                     ((info.Height - rectResolution) / 2) + rectResolution);

            const float startAngle = -270.0f + MeterSpaceAngle;
            const float sweepAngle = 360.0f - 2.0f * MeterSpaceAngle;

            // Base
            var basePaint = new SKPaint
            {
                TextSize    = 64.0f,
                IsAntialias = true,
                Color       = new SKColor(192, 204, 218),
                Style       = SKPaintStyle.Stroke,
                StrokeWidth = MeterThickness
            };

            SKPath basePath = new SKPath();

            basePath.AddArc(rect, startAngle, sweepAngle);
            canvas.DrawPath(basePath, basePaint);

            // Velocity
            float velocityAngle = (float)Math.Min(Math.Max((sweepAngle * velocity) / MeterMaxVelocity, 0.0f), sweepAngle);

            var velocityPaint = new SKPaint
            {
                TextSize    = 64.0f,
                IsAntialias = true,
                Color       = new SKColor(230, 100, 100),
                Style       = SKPaintStyle.Stroke,
                StrokeWidth = MeterThickness
            };

            SKPath velocityPath = new SKPath();

            velocityPath.AddArc(rect, startAngle, velocityAngle);
            canvas.DrawPath(velocityPath, velocityPaint);

            // Text
            var velocityTextPaint = new SKPaint
            {
                TextSize    = 256.0f,
                IsAntialias = true,
                Color       = new SKColor(230, 100, 100),
                Style       = SKPaintStyle.Fill,
                TextAlign   = SKTextAlign.Center
            };

            canvas.DrawText(Math.Round(velocity).ToString(), info.Width / 2.0f, (drawResolution / 2.0f) + 80.0f, velocityTextPaint);

            var unitTextPaint = new SKPaint
            {
                TextSize    = 80.0f,
                IsAntialias = true,
                Color       = new SKColor(192, 204, 218),
                Style       = SKPaintStyle.Fill,
                TextAlign   = SKTextAlign.Center
            };

            canvas.DrawText("km/h", info.Width / 2.0f, (drawResolution / 2.0f) + 300.0f, unitTextPaint);
        }
Пример #22
0
        private float DrawAxes(SKCanvas canvas, SKRect chartRect)
        {
            float maxValue = 0;

            foreach (var series in _chartData.SeriesCollection)
            {
                var seriesMax = series.DataPoints.Max(d => d.Value);
                maxValue = Math.Max(maxValue, seriesMax);
            }

            int highest = (int)Math.Round(maxValue / 10.0, MidpointRounding.AwayFromZero) * 10;

            int nextHighest = highest;

            int height = (int)chartRect.Height;

            int   markerValue  = nextHighest / 4;
            float markerOffset = height / 4;

            float x = chartRect.Left;
            float y = chartRect.Top + _chartData.TextFont.TextSize;

            var axesPaint = new SKPaint
            {
                Color       = SKColors.Black,
                StrokeWidth = 1,
                Style       = SKPaintStyle.Stroke,
                IsAntialias = true,
            };

            var linePaint = new SKPaint
            {
                Color       = SKColors.LightGray,
                StrokeWidth = 1,
                Style       = SKPaintStyle.Stroke,
                IsAntialias = true,
            };


            List <string> texts = new List <string>();

            float maxWidth = BuildAxesLabels(nextHighest, markerValue, texts);

            canvas.Save();
            canvas.Translate(maxWidth, 0);
            TextPaint.TextAlign = SKTextAlign.Right;

            for (int i = 0; i < 5; i++)
            {
                y = chartRect.Top + i * markerOffset;
                canvas.DrawText(texts[i], x, y + _chartData.TextFont.TextSize / 2, TextPaint);

                if (i != 4)
                {
                    canvas.DrawLine(x + _chartData.TextFont.TextSize, y, chartRect.Right, y, linePaint);
                }
            }

            SKPath path = new SKPath();

            path.MoveTo(x + _chartData.TextFont.TextSize, chartRect.Top);
            path.LineTo(x + _chartData.TextFont.TextSize, chartRect.Bottom);
            path.LineTo(chartRect.Right - maxWidth, chartRect.Bottom);

            canvas.DrawPath(path, axesPaint);

            canvas.Restore();

            float unitHeight = height / (float)highest;

            return(unitHeight);
        }
Пример #23
0
        private void PaintLens(object sender, SKPaintSurfaceEventArgs args)
        {
            analyzeLensResponseDTO analyzeLensResponseDTO = RightLens.Equals(sender) ? model.RightAnalyzeLensResponse : model.LeftAnalyzeLensResponse;

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

            canvas.Clear();

            SKPaint blackSKPaint = new SKPaint
            {
                Style = SKPaintStyle.Fill,
                Color = SKColors.Black
            };

            canvas.DrawRect(new SKRect(0, 0, info.Width, info.Height), blackSKPaint);

            if (analyzeLensResponseDTO != null && analyzeLensResponseDTO.points != null & analyzeLensResponseDTO.points.Any())
            {
                int sqrt = Convert.ToInt32(Math.Sqrt(analyzeLensResponseDTO.points.Count()));
                int side = (sqrt - 1) / 2;

                ICollection <analyzedPointDTO> points = analyzeLensResponseDTO.points.Where(p => IsInside(p, side + 1)).ToList();

                double max = compare && model.RightAnalyzeLensResponse != null && model.LeftAnalyzeLensResponse != null?Math.Max(model.RightAnalyzeLensResponse.points.Where(p => IsInside(p, side + 1)).Select(mapping).Max(), model.LeftAnalyzeLensResponse.points.Where(p => IsInside(p, side + 1)).Select(mapping).Max()) : points.Where(p => IsInside(p, side + 1)).Select(mapping).Max();

                double min = compare && model.RightAnalyzeLensResponse != null && model.LeftAnalyzeLensResponse != null?Math.Min(model.RightAnalyzeLensResponse.points.Where(p => IsInside(p, side + 1)).Select(mapping).Min(), model.LeftAnalyzeLensResponse.points.Where(p => IsInside(p, side + 1)).Select(mapping).Min()) : points.Where(p => IsInside(p, side + 1)).Select(mapping).Min();

                double range = (max - min) / 6.0;

                if (range > 0)
                {
                    double centerX    = info.Width / 2.0;
                    double centerY    = info.Height / 2.0;
                    double bitmapSide = Math.Min(centerX, centerY);
                    double radius     = bitmapSide * 5 / 6;

                    double doubleRange = range * 2;
                    double tripleRange = range * 3;
                    double fiveRange   = range * 5;

                    double sqrtRange       = sqrt / 6.0;
                    double doubleSqrtRange = sqrtRange * 2;
                    double tripleSqrtRange = sqrtRange * 3;
                    double fiveSqrtRange   = sqrtRange * 5;

                    using (SKBitmap bitmap = new SKBitmap(1, sqrt))
                    {
                        for (int i = sqrt - 1; i >= 0; i--)
                        {
                            SKColor color = SKColors.Black;

                            switch (Math.Floor(i / sqrtRange))
                            {
                            case 0:
                                color = new SKColor(Convert.ToByte(Math.Round(i / sqrtRange * 255)), Convert.ToByte(Math.Round(i / sqrtRange * 255)), 255);
                                break;

                            case 1:
                                color = new SKColor(Convert.ToByte(Math.Round((doubleSqrtRange - i) / sqrtRange * 255)), 255, 255);
                                break;

                            case 2:
                                color = new SKColor(0, 255, Convert.ToByte(Math.Round((tripleSqrtRange - i) / sqrtRange * 255)));
                                break;

                            case 3:
                                color = new SKColor(Convert.ToByte(Math.Round((i - tripleSqrtRange) / sqrtRange * 255)), 255, 0);
                                break;

                            case 4:
                                color = new SKColor(255, Convert.ToByte(Math.Round((fiveSqrtRange - i) / sqrtRange * 255)), 0);
                                break;

                            default:
                                color = new SKColor(255, 0, Convert.ToByte(Math.Round((i - fiveSqrtRange) / sqrtRange * 255)));
                                break;
                            }

                            bitmap.SetPixel(0, i, color);
                        }

                        canvas.DrawBitmap(bitmap.Resize(new SKImageInfo(Convert.ToInt32(bitmapSide / 6.0), Convert.ToInt32(bitmapSide)), SKBitmapResizeMethod.Mitchell), new SKRect(Convert.ToSingle(info.Width - bitmapSide / 6.0), 0, Convert.ToSingle(info.Width), info.Height));
                    }

                    blackSKPaint.TextSize = info.Height / 32f;

                    float textRange = (info.Height - blackSKPaint.TextSize * 3) / 6f;

                    canvas.DrawText(string.Format("{0:N2}", min), Convert.ToSingle(info.Width - bitmapSide / 8), blackSKPaint.TextSize * 2, blackSKPaint);
                    canvas.DrawText(string.Format("{0:N2}", min + range), Convert.ToSingle(info.Width - bitmapSide / 8), blackSKPaint.TextSize * 2 + textRange, blackSKPaint);
                    canvas.DrawText(string.Format("{0:N2}", min + range * 2), Convert.ToSingle(info.Width - bitmapSide / 8), blackSKPaint.TextSize * 2 + textRange * 2, blackSKPaint);
                    canvas.DrawText(string.Format("{0:N2}", min + range * 3), Convert.ToSingle(info.Width - bitmapSide / 8), blackSKPaint.TextSize * 2 + textRange * 3, blackSKPaint);
                    canvas.DrawText(string.Format("{0:N2}", min + range * 4), Convert.ToSingle(info.Width - bitmapSide / 8), blackSKPaint.TextSize * 2 + textRange * 4, blackSKPaint);
                    canvas.DrawText(string.Format("{0:N2}", min + range * 5), Convert.ToSingle(info.Width - bitmapSide / 8), blackSKPaint.TextSize * 2 + textRange * 5, blackSKPaint);
                    canvas.DrawText(string.Format("{0:N2}", max), Convert.ToSingle(info.Width - bitmapSide / 8), blackSKPaint.TextSize * 2 + textRange * 6, blackSKPaint);

                    using (SKBitmap bitmap = new SKBitmap(sqrt, sqrt))
                    {
                        foreach (analyzedPointDTO point in points)
                        {
                            SKColor color = SKColors.Black;

                            double value = mapping.Invoke(point) - min;

                            switch (Math.Floor(value / range))
                            {
                            case 0:
                                color = new SKColor(Convert.ToByte(Math.Round(value / range * 255)), Convert.ToByte(Math.Round(value / range * 255)), 255);
                                break;

                            case 1:
                                color = new SKColor(Convert.ToByte(Math.Round((doubleRange - value) / range * 255)), 255, 255);
                                break;

                            case 2:
                                color = new SKColor(0, 255, Convert.ToByte(Math.Round((tripleRange - value) / range * 255)));
                                break;

                            case 3:
                                color = new SKColor(Convert.ToByte(Math.Round((value - tripleRange) / range * 255)), 255, 0);
                                break;

                            case 4:
                                color = new SKColor(255, Convert.ToByte(Math.Round((fiveRange - value) / range * 255)), 0);
                                break;

                            default:
                                color = new SKColor(255, 0, Convert.ToByte(Math.Round((value - fiveRange) / range * 255)));
                                break;
                            }

                            bitmap.SetPixel(Convert.ToInt32(side - point.x), Convert.ToInt32(side - point.y), color);
                        }

                        if (mask)
                        {
                            using (SKPath path = new SKPath())
                            {
                                path.AddCircle(Convert.ToSingle(centerX), Convert.ToSingle(centerY), Convert.ToSingle(radius));
                                canvas.ClipPath(path, SKClipOperation.Intersect);
                            }
                        }

                        canvas.DrawBitmap(bitmap.Resize(new SKImageInfo(Convert.ToInt32(radius), Convert.ToInt32(radius)), SKBitmapResizeMethod.Mitchell), new SKRect(Convert.ToSingle(centerX - radius), Convert.ToSingle(centerY - radius), Convert.ToSingle(centerX + radius), Convert.ToSingle(centerY + radius)));
                    }
                }
            }
        }
Пример #24
0
        protected void DrawYLabels(SKCanvas canvas, float height, float headerHeight)
        {
            if (!this.ShowYLabels)
            {
                return;
            }

            float yLabelHeight = this.ComputeYLabelHeight();

            if (yLabelHeight <= 0.1f)
            {
                return;
            }

            int   linesCount        = (int)Math.Floor(height / yLabelHeight);
            float gridLinesInterval = height / linesCount;
            float valueDelta        = ValueRange / linesCount;

            if (!this.ShowYLabelOnAllRows)
            {
                float minY = headerHeight + height;
                float maxY = headerHeight;

                var minYLabel = MinValue.ToString("0.0") + this.YUnitMeasure;
                if (!string.IsNullOrEmpty(minYLabel))
                {
                    using (var paint = new SKPaint())
                    {
                        paint.Typeface     = this.Typeface;
                        paint.TextEncoding = this.TextEncoding;
                        paint.TextSize     = this.LabelTextSize;
                        paint.IsAntialias  = true;
                        paint.Color        = this.YLabelsColor;
                        paint.IsStroke     = false;

                        var bounds = new SKRect();
                        var text   = minYLabel;
                        paint.MeasureText(text, ref bounds);

                        canvas.DrawText(text, this.Margin, minY + (bounds.Height / 2), paint);
                    }
                }

                var maxYLabel = MaxValue.ToString("0.0") + this.YUnitMeasure;
                if (!string.IsNullOrEmpty(maxYLabel))
                {
                    using (var paint = new SKPaint())
                    {
                        paint.Typeface     = this.Typeface;
                        paint.TextEncoding = this.TextEncoding;
                        paint.TextSize     = this.LabelTextSize;
                        paint.IsAntialias  = true;
                        paint.Color        = this.YLabelsColor;
                        paint.IsStroke     = false;

                        var bounds = new SKRect();
                        var text   = maxYLabel;
                        paint.MeasureText(text, ref bounds);

                        canvas.DrawText(text, this.Margin, maxY + (bounds.Height / 2), paint);
                    }
                }
            }
            else
            {
                for (int i = 0; i <= linesCount; i++)
                {
                    var value = Math.Round(this.MinValue + (valueDelta * i), 1);
                    var label = value.ToString("0.0") + this.YUnitMeasure;

                    using (var paint = new SKPaint())
                    {
                        float y = headerHeight + height - (gridLinesInterval * i);

                        paint.Typeface     = this.Typeface;
                        paint.TextEncoding = this.TextEncoding;
                        paint.TextSize     = this.LabelTextSize;
                        paint.IsAntialias  = true;
                        paint.Color        = this.YLabelsColor;
                        paint.IsStroke     = false;

                        var bounds = new SKRect();
                        paint.MeasureText(label, ref bounds);

                        canvas.DrawText(label, this.Margin, y + (bounds.Height / 2), paint);
                    }
                }
            }
        }
Пример #25
0
        public void Render(SKCanvas canvas, float canvasWidth, float canvasHeight)
        {
            canvas.Clear(new SKColor(0xFFFFFFFF));

            const float margin = 80;


            float?height = (float)(canvasHeight - margin * 2);
            float?width  = (float)(canvasWidth - margin * 2);

            //width = 25;

            if (!UseMaxHeight)
            {
                height = null;
            }
            if (!UseMaxWidth)
            {
                width = null;
            }

            using (var gridlinePaint = new SKPaint()
            {
                Color = new SKColor(0xFFFF0000), StrokeWidth = 1
            })
            {
                canvas.DrawLine(new SKPoint(margin, 0), new SKPoint(margin, (float)canvasHeight), gridlinePaint);
                if (width.HasValue)
                {
                    canvas.DrawLine(new SKPoint(margin + width.Value, 0), new SKPoint(margin + width.Value, (float)canvasHeight), gridlinePaint);
                }
                canvas.DrawLine(new SKPoint(0, margin), new SKPoint((float)canvasWidth, margin), gridlinePaint);
                if (height.HasValue)
                {
                    canvas.DrawLine(new SKPoint(0, margin + height.Value), new SKPoint((float)canvasWidth, margin + height.Value), gridlinePaint);
                }
            }

            //string typefaceName = "Times New Roman";
            string typefaceName = "Segoe UI";
            //string typefaceName = "Segoe Script";

            var styleNormal = new Style()
            {
                FontFamily = typefaceName, FontSize = 18 * Scale
            };
            var styleSmall       = styleNormal.Modify(fontSize: 12 * Scale);
            var styleScript      = styleNormal.Modify(fontFamily: "Segoe Script");
            var styleHeading     = styleNormal.Modify(fontSize: 24 * Scale, fontWeight: 700);
            var styleFixedPitch  = styleNormal.Modify(fontFamily: "Courier New");
            var styleLTR         = styleNormal.Modify(textDirection: TextDirection.LTR);
            var styleBold        = styleNormal.Modify(fontWeight: 700);
            var styleUnderline   = styleNormal.Modify(underline: UnderlineStyle.Gapped, textColor: new SKColor(0xFFFF0000));
            var styleStrike      = styleNormal.Modify(strikeThrough: StrikeThroughStyle.Solid);
            var styleSubScript   = styleNormal.Modify(fontVariant: FontVariant.SubScript);
            var styleSuperScript = styleNormal.Modify(fontVariant: FontVariant.SuperScript);
            var styleItalic      = styleNormal.Modify(fontItalic: true);
            var styleBoldLarge   = styleNormal.Modify(fontSize: 28 * Scale, fontWeight: 700);
            var styleRed         = styleNormal.Modify(textColor: new SKColor(0xFFFF0000));
            var styleBlue        = styleNormal.Modify(textColor: new SKColor(0xFF0000FF));
            var styleFontAwesome = new Style()
            {
                FontFamily = "FontAwesome", FontSize = 24 * Scale
            };


            _textBlock.Clear();
            _textBlock.MaxWidth  = width;
            _textBlock.MaxHeight = height;

            _textBlock.BaseDirection = BaseDirection;
            _textBlock.Alignment     = TextAlignment;

            switch (ContentMode)
            {
            case 0:
                _textBlock.AddText("Welcome to RichTextKit!\n", styleHeading);
                _textBlock.AddText("\nRichTextKit is a rich text layout, rendering and measurement library for SkiaSharp.\n\nIt supports normal, ", styleNormal);
                _textBlock.AddText("bold", styleBold);
                _textBlock.AddText(", ", styleNormal);
                _textBlock.AddText("italic", styleItalic);
                _textBlock.AddText(", ", styleNormal);
                _textBlock.AddText("underline", styleUnderline);
                _textBlock.AddText(" (including ", styleNormal);
                _textBlock.AddText("gaps over descenders", styleUnderline);
                _textBlock.AddText("), ", styleNormal);
                _textBlock.AddText("strikethrough", styleStrike);
                _textBlock.AddText(", superscript (E=mc", styleNormal);
                _textBlock.AddText("2", styleSuperScript);
                _textBlock.AddText("), subscript (H", styleNormal);
                _textBlock.AddText("2", styleSubScript);
                _textBlock.AddText("O), ", styleNormal);
                _textBlock.AddText("colored ", styleRed);
                _textBlock.AddText("text", styleBlue);
                _textBlock.AddText(" and ", styleNormal);
                _textBlock.AddText("mixed ", styleNormal);
                _textBlock.AddText("sizes", styleSmall);
                _textBlock.AddText(" and ", styleNormal);
                _textBlock.AddText("fonts", styleScript);
                _textBlock.AddText(".\n\n", styleNormal);
                _textBlock.AddText("Font fallback means emojis work: 🌐 🍪 🍕 🚀 and ", styleNormal);
                _textBlock.AddText("text shaping and bi-directional text support means complex scripts and languages like Arabic: مرحبا بالعالم, Japanese: ハローワールド, Chinese: 世界您好 and Hindi: हैलो वर्ल्ड are rendered correctly!\n\n", styleNormal);
                _textBlock.AddText("RichTextKit also supports left/center/right text alignment, word wrapping, truncation with ellipsis place-holder, text measurement, hit testing, painting a selection range, caret position & shape helpers.", styleNormal);
                break;

            case 1:
                _textBlock.AddText("\n\n", styleNormal);
                //_textBlock.AddEllipsis();

                /*
                 * _textBlock.AddText("Hello Wor", styleNormal);
                 * _textBlock.AddText("ld", styleRed);
                 * _textBlock.AddText(". This is normal 18px. These are emojis: 🌐 🍪 🍕 🚀 🏴‍☠️", styleNormal);
                 * _textBlock.AddText("This is ", styleNormal);
                 * _textBlock.AddText("bold 28px", styleBoldLarge);
                 * _textBlock.AddText(". ", styleNormal);
                 * _textBlock.AddText("This is italic", styleItalic);
                 * _textBlock.AddText(". This is ", styleNormal);
                 * _textBlock.AddText("red", styleRed);
                 * _textBlock.AddText(". This is Arabic: (", styleNormal);
                 * _textBlock.AddText("تسجّل ", styleNormal);
                 * _textBlock.AddText("يتكلّم", styleNormal);
                 * _textBlock.AddText("), Hindi: ", styleNormal);
                 * _textBlock.AddText("हालाँकि प्रचलित रूप पूज", styleNormal);
                 * _textBlock.AddText(", Han: ", styleNormal);
                 * _textBlock.AddText("緳 踥踕", styleNormal);
                 */
                break;

            case 2:
                _textBlock.AddText("Hello Wor", styleNormal);
                _textBlock.AddText("ld", styleRed);
                _textBlock.AddText(".\nThis is normal 18px.\nThese are emojis: 🌐 🍪 🍕 🚀\n", styleNormal);
                _textBlock.AddText("This is ", styleNormal);
                _textBlock.AddText("bold 28px", styleBoldLarge);
                _textBlock.AddText(".\n", styleNormal);
                _textBlock.AddText("This is italic", styleItalic);
                _textBlock.AddText(".\nThis is ", styleNormal);
                _textBlock.AddText("red", styleRed);

                /*
                 * tle.AddText(".\nThis is Arabic: (", styleNormal);
                 * tle.AddText("تسجّل ", styleNormal);
                 * tle.AddText("يتكلّم", styleNormal);
                 * tle.AddText("), Hindi: ", styleNormal);
                 */
                _textBlock.AddText(".\nThis is Arabic: (تسجّل يتكلّم), Hindi: ", styleNormal);
                _textBlock.AddText("हालाँकि प्रचलित रूप पूज", styleNormal);
                _textBlock.AddText(", Han: ", styleNormal);
                _textBlock.AddText("緳 踥踕", styleNormal);
                break;

            case 3:
                _textBlock.AddText("Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus semper, sapien vitae placerat sollicitudin, lorem diam aliquet quam, id finibus nisi quam eget lorem.\nDonec facilisis sem nec rhoncus elementum. Cras laoreet porttitor malesuada.\n\nVestibulum sed lacinia diam. Mauris a mollis enim. Cras in rhoncus mauris, at vulputate nisl. Sed nec lobortis dolor, hendrerit posuere quam. Vivamus malesuada sit amet nunc ac cursus. Praesent volutpat euismod efficitur. Nam eu ante.", styleNormal);
                break;

            case 4:
                //_textBlock.AddText("مرحبا بالعالم.  هذا هو اختبار التفاف \nالخط للتأكد من أنه يعمل للغات من اليمين إلى اليسار.\n", styleNormal);
                _textBlock.AddText("مرحبا بالعالم.  هذا هو اختبار التفاف \n", styleNormal);
                _textBlock.AddText("مرحبا بالعالم.  هذا هو اختبار الت", styleNormal);
                _textBlock.AddText("فاف \n", styleUnderline);
                break;

            case 5:
                //_textBlock.AddText("مرحبا بالعالم.  هذا هو اختبار التفاف الخط للتأكد من \u2066ACME Inc.\u2069 أنه يعمل للغات من اليمين إلى اليسار.", styleNormal);
                _textBlock.AddText("مرحبا بالعالم.  هذا هو اختبار التفاف الخط للتأكد من ", styleNormal);
                _textBlock.AddText("ACME Inc.", styleLTR);
                _textBlock.AddText(" أنه يعمل للغات من اليمين إلى اليسار.", styleNormal);
                break;

            case 6:
                _textBlock.AddText("Subscript: H", styleNormal);
                _textBlock.AddText("2", styleSubScript);
                _textBlock.AddText("O  Superscript: E=mc", styleNormal);
                _textBlock.AddText("2", styleSuperScript);
                _textBlock.AddText("  Key: C", styleNormal);
                _textBlock.AddText("♯", styleSuperScript);
                _textBlock.AddText(" B", styleNormal);
                _textBlock.AddText("♭", styleSubScript);
                break;

            case 7:
                _textBlock.AddText("The quick brown fox jumps over the lazy dog.", styleUnderline);
                _textBlock.AddText(" ", styleNormal);
                _textBlock.AddText("Strike Through", styleStrike);
                _textBlock.AddText(" something ends in wooooooooq", styleNormal);
                break;

            case 8:
                _textBlock.AddText("Apples and Bananas\r\n", styleNormal);
                _textBlock.AddText("Pears\r\n", styleNormal);
                _textBlock.AddText("Bananas\r\n", styleNormal);
                break;

            case 9:
                _textBlock.AddText("Toggle Theme\r\n", styleNormal);
                _textBlock.AddText("T", styleUnderline);
                _textBlock.AddText("oggle Theme\r\n", styleNormal);
                break;

            case 10:
                _textBlock.AddText("", styleNormal);
                break;

            case 11:
                _textBlock.AddText("\uF06B", styleFontAwesome);
                break;

            case 12:
                _textBlock.AddText(".|.|.|.|.|.|.|.|.|.|.|.|.|.|.|.|.|.|.|.|.|.|.|.|.|.|.|.|.|.|\n", styleFixedPitch);
                _textBlock.AddText("♩♩♩♩♩♩♩♩♩♩♩\n", styleFixedPitch);
                _textBlock.AddText("\n", styleFixedPitch);
                _textBlock.AddText("   ♩__♩__♩.       ♩.     ♩.       x4\n", styleFixedPitch);
                _textBlock.AddText("   ♩__♩__♩.       ♩.     ♩.       x4\n", styleFixedPitch);
                _textBlock.AddText("   ♩   ♩   ♩.       ♩ ♪   ♩ ♪     x4\n", styleFixedPitch);
                _textBlock.AddText("   ♩   ♩   ♩   ♪   ♩ ♪   ♩ ♪      x8\n", styleFixedPitch);
                _textBlock.AddText("\n", styleFixedPitch);
                _textBlock.AddText("   🌐 🍪 🍕 🚀 🏴‍☠️ xxx\n", styleFixedPitch);
                _textBlock.AddText("   🌐 🍪 🍕 🚀    xxx\n", styleFixedPitch);
                _textBlock.AddText("   🌐🍪🍕🚀       xxx\n", styleFixedPitch);

                break;
            }

            var sw = new Stopwatch();

            sw.Start();
            _textBlock.Layout();
            var elapsed = sw.ElapsedMilliseconds;

            var options = new TextPaintOptions()
            {
                SelectionColor = new SKColor(0x60FF0000),
            };

            HitTestResult?htr = null;
            CaretInfo?    ci  = null;

            if (_showHitTest)
            {
                htr = _textBlock.HitTest(_hitTestX - margin, _hitTestY - margin);
                if (htr.Value.OverCodePointIndex >= 0)
                {
                    options.SelectionStart = htr.Value.OverCodePointIndex;
                    options.SelectionEnd   = _textBlock.CaretIndicies[_textBlock.LookupCaretIndex(htr.Value.OverCodePointIndex) + 1];
                }

                ci = _textBlock.GetCaretInfo(htr.Value.ClosestCodePointIndex);
            }

            if (ShowMeasuredSize)
            {
                using (var paint = new SKPaint()
                {
                    Color = new SKColor(0x1000FF00),
                    IsStroke = false,
                })
                {
                    var rect = new SKRect(margin + _textBlock.MeasuredPadding.Left, margin, margin + _textBlock.MeasuredWidth + _textBlock.MeasuredPadding.Left, margin + _textBlock.MeasuredHeight);
                    canvas.DrawRect(rect, paint);
                }
            }

            if (_textBlock.MeasuredOverhang.Left > 0)
            {
                using (var paint = new SKPaint()
                {
                    Color = new SKColor(0xFF00fff0), StrokeWidth = 1
                })
                {
                    canvas.DrawLine(new SKPoint(margin - _textBlock.MeasuredOverhang.Left, 0), new SKPoint(margin - _textBlock.MeasuredOverhang.Left, (float)canvasHeight), paint);
                }
            }

            if (_textBlock.MeasuredOverhang.Right > 0)
            {
                using (var paint = new SKPaint()
                {
                    Color = new SKColor(0xFF00ff00), StrokeWidth = 1
                })
                {
                    float x;
                    if (_textBlock.MaxWidth.HasValue)
                    {
                        x = margin + _textBlock.MaxWidth.Value;
                    }
                    else
                    {
                        x = margin + _textBlock.MeasuredWidth;
                    }
                    x += _textBlock.MeasuredOverhang.Right;
                    canvas.DrawLine(new SKPoint(x, 0), new SKPoint(x, (float)canvasHeight), paint);
                }
            }

            _textBlock.Paint(canvas, new SKPoint(margin, margin), options);

            if (ci != null)
            {
                using (var paint = new SKPaint()
                {
                    Color = new SKColor(0xFF000000),
                    IsStroke = true,
                    IsAntialias = true,
                    StrokeWidth = Scale,
                })
                {
                    var rect = ci.Value.CaretRectangle;
                    rect.Offset(margin, margin);
                    canvas.DrawLine(rect.Right, rect.Top, rect.Left, rect.Bottom, paint);
                }
            }

            var state = $"Size: {width} x {height} Base Direction: {BaseDirection} Alignment: {TextAlignment} Content: {ContentMode} scale: {Scale} time: {elapsed}";

            canvas.DrawText(state, margin, 20, new SKPaint()
            {
                Typeface    = SKTypeface.FromFamilyName("Arial"),
                TextSize    = 12,
                IsAntialias = true,
            });

            state = $"Selection: {options.SelectionStart}-{options.SelectionEnd} Closest: {(htr.HasValue ? htr.Value.ClosestCodePointIndex.ToString() : "-")}";
            canvas.DrawText(state, margin, 40, new SKPaint()
            {
                Typeface    = SKTypeface.FromFamilyName("Arial"),
                TextSize    = 12,
                IsAntialias = true,
            });

            state = $"Measured: {_textBlock.MeasuredWidth} x {_textBlock.MeasuredHeight} Lines: {_textBlock.Lines.Count} Truncated: {_textBlock.Truncated}";
            canvas.DrawText(state, margin, 60, new SKPaint()
            {
                Typeface    = SKTypeface.FromFamilyName("Arial"),
                TextSize    = 12,
                IsAntialias = true,
            });
        }
Пример #26
0
        private void DrawMarker(SKCanvas canvas, Marker marker)
        {
            SKRectI bounds     = new SKRectI();
            double  topLeftLat = tiles[0].Tile_lat;
            double  topLeftLon = tiles[0].Tile_lon;

            bool gotBounds = canvas.GetDeviceClipBounds(out bounds);

            double distanceFromCentreLat = marker.Position.Latitude - App.CurrentCentre.Latitude;
            double pixelsFromCentreLat   = distanceFromCentreLat / App.CurrentLatDegreesPerPixel;
            double yOff = (pixelsFromCentreLat * -1) + (bounds.MidY / App.ZoomScale);

            double distanceFromCentreLon = marker.Position.Longitude - App.CurrentCentre.Longitude;
            double pixelsFromCentreLon   = distanceFromCentreLon / App.CurrentLonDegreesPerPixel;
            double xOff = pixelsFromCentreLon + (bounds.MidX / App.ZoomScale);

            float x = Convert.ToSingle(xOff);
            float y = Convert.ToSingle(yOff);

            SKColor pointerColor = SKColors.White;

            marker.Point = new SKPoint(x, y);
            SKPaint circlePaint = new SKPaint();

            switch (marker.Type)
            {
            case MarkerType.Step:
                // Create circle fill


                circlePaint.Style       = SKPaintStyle.Fill;
                circlePaint.Color       = SKColors.White;
                circlePaint.IsAntialias = true;

                canvas.DrawCircle(x, y - 30, 18, circlePaint);



                // circle stroke
                circlePaint.Style       = SKPaintStyle.Stroke;
                circlePaint.StrokeWidth = 5.0f;
                circlePaint.Color       = SKColors.Red;
                circlePaint.IsAntialias = true;
                canvas.DrawCircle(x, y - 30, 18, circlePaint);

                // Add Text
                SKPaint textPaint = new SKPaint()
                {
                    TextSize    = 16.0f,
                    IsAntialias = true,
                    Color       = SKColors.Black,
                    Style       = SKPaintStyle.StrokeAndFill,
                    StrokeWidth = 1,
                    TextAlign   = SKTextAlign.Center
                };
                canvas.DrawText(marker.Number, x, y - 30 + (textPaint.TextSize / 2) - 2, textPaint);

                pointerColor = SKColors.Red;
                break;

            case MarkerType.Search:
                // Create circle fill


                circlePaint.Style       = SKPaintStyle.Fill;
                circlePaint.Color       = SKColors.Blue;
                circlePaint.IsAntialias = true;

                canvas.DrawCircle(x, y - 30, 18, circlePaint);



                // circle stroke
                circlePaint.Style       = SKPaintStyle.Stroke;
                circlePaint.StrokeWidth = 5.0f;
                circlePaint.Color       = SKColors.Blue;
                circlePaint.IsAntialias = true;
                canvas.DrawCircle(x, y - 30, 18, circlePaint);
                pointerColor = SKColors.Blue;
                break;

            case MarkerType.Gardens:
                // Create circle fill
                circlePaint.Style       = SKPaintStyle.Fill;
                circlePaint.Color       = SKColors.LightBlue;
                circlePaint.IsAntialias = true;
                canvas.DrawCircle(x, y - 30, 18, circlePaint);
                // circle stroke
                circlePaint.Style       = SKPaintStyle.Stroke;
                circlePaint.StrokeWidth = 5.0f;
                circlePaint.Color       = SKColors.Green;
                circlePaint.IsAntialias = true;
                canvas.DrawCircle(x, y - 30, 18, circlePaint);
                // draw flower
                circlePaint.Style = SKPaintStyle.Fill;
                //stalk
                circlePaint.Color = SKColors.Green;
                canvas.DrawRect(x - 1, y - 28, 2, 12, circlePaint);
                //petals
                circlePaint.Color = SKColors.Yellow;
                canvas.DrawCircle(x - 4, y - 34, 6, circlePaint);
                canvas.DrawCircle(x + 4, y - 34, 6, circlePaint);
                canvas.DrawCircle(x - 4, y - 30, 6, circlePaint);
                canvas.DrawCircle(x + 4, y - 30, 6, circlePaint);
                //centre
                circlePaint.Color = SKColors.Orange;
                canvas.DrawCircle(x, y - 32, 4, circlePaint);

                pointerColor = SKColors.Green;
                break;

            case MarkerType.Landscape:
                float x1 = x - 18;
                float y1 = y - 23;
                float x2 = x - 12;
                float y2 = y - 29;
                float x3 = x - 8;
                float y3 = y - 34;
                float x4 = x - 5;
                float y4 = y - 30;
                float x5 = x + 5;
                float y5 = y - 26;
                float x6 = x + 18;
                float y6 = y - 22;

                // Create circle fill
                circlePaint.Style       = SKPaintStyle.Fill;
                circlePaint.Color       = SKColors.LightBlue;
                circlePaint.IsAntialias = true;
                canvas.DrawCircle(x, y - 30, 18, circlePaint);
                circlePaint.Color       = SKColors.SandyBrown;
                circlePaint.Style       = SKPaintStyle.Stroke;
                circlePaint.StrokeWidth = 5;
                SKPath landPath1 = new SKPath();
                landPath1.MoveTo(x1, y1);
                landPath1.LineTo(x2, y2);
                landPath1.LineTo(x3, y3);
                landPath1.LineTo(x4, y4);
                landPath1.LineTo(x5, y5);
                landPath1.LineTo(x6, y6);
                canvas.DrawPath(landPath1, circlePaint);
                circlePaint.Color = SKColors.Green;
                SKPath landPath2 = new SKPath();
                landPath2.MoveTo(x1 + 3, y1 + 5);
                landPath2.LineTo(x2, y2 + 5);
                landPath2.LineTo(x3, y3 + 5);
                landPath2.LineTo(x4, y4 + 5);
                landPath2.LineTo(x5, y5 + 5);
                landPath2.LineTo(x6 - 2, y6 + 4);
                canvas.DrawPath(landPath2, circlePaint);
                circlePaint.Color = SKColors.DarkGreen;
                circlePaint.Style = SKPaintStyle.StrokeAndFill;
                SKPath landPath3 = new SKPath();
                landPath3.MoveTo(x1 + 8, y1 + 9);
                landPath3.LineTo(x2, y2 + 8);
                landPath3.LineTo(x3, y3 + 10);
                landPath3.LineTo(x4, y4 + 10);
                landPath3.LineTo(x5, y5 + 10);
                landPath3.LineTo(x6 - 6, y6 + 7);
                canvas.DrawPath(landPath3, circlePaint);
                // circle stroke
                circlePaint.Style       = SKPaintStyle.Stroke;
                circlePaint.StrokeWidth = 5.0f;
                circlePaint.Color       = SKColors.Green;
                circlePaint.IsAntialias = true;
                canvas.DrawCircle(x, y - 30, 18, circlePaint);


                pointerColor = SKColors.Green;
                break;

            case MarkerType.House:
                // create house
                // roof
                SKPath roofPath = new SKPath();
                roofPath.MoveTo(x - 13, y - 30);
                roofPath.LineTo(x - 11, y - 41);
                roofPath.LineTo(x + 10, y - 41);
                roofPath.LineTo(x + 12, y - 30);
                roofPath.LineTo(x - 13, y - 30);


                SKPaint roofPaint = new SKPaint
                {
                    Style       = SKPaintStyle.StrokeAndFill,
                    Color       = SKColors.SlateGray,
                    IsAntialias = true,
                    StrokeWidth = 1
                };
                canvas.DrawPath(roofPath, roofPaint);

                // building
                SKPaint rectPaint = new SKPaint
                {
                    Style       = SKPaintStyle.Fill,
                    Color       = SKColors.Firebrick,
                    IsAntialias = true
                };
                canvas.DrawRect(x - 11, y - 30, 21, 21, rectPaint);
                pointerColor = SKColors.Firebrick;

                // door
                SKPaint doorPaint = new SKPaint
                {
                    Style = SKPaintStyle.Fill,
                    Color = SKColors.DarkBlue
                };
                canvas.DrawRect(x - 2, y - 16, 4, 12, doorPaint);
                // window
                SKPaint windowPaint = new SKPaint
                {
                    Style = SKPaintStyle.Fill,
                    Color = SKColors.LightCyan
                };
                canvas.DrawRect(x - 8, y - 24, 5, 4, windowPaint);
                canvas.DrawRect(x + 2, y - 24, 5, 4, windowPaint);
                break;
            }
            //Add pointer

            // Create the path
            SKPath pointerPath = new SKPath();

            pointerPath.MoveTo(x, y);
            pointerPath.LineTo(x - 4, y - 9);
            pointerPath.LineTo(x + 4, y - 9);
            pointerPath.LineTo(x, y);
            // Create two SKPaint objects
            SKPaint pointerPaint = new SKPaint
            {
                Style       = SKPaintStyle.StrokeAndFill,
                Color       = pointerColor,
                IsAntialias = true,
                StrokeWidth = 1
            };

            canvas.DrawPath(pointerPath, pointerPaint);
        }
Пример #27
0
    private Stream CreateBarChartImage(BarChartDrawingData barChartDrawingData,
                                       DiscordRoleId primaryGameDiscordRoleId,
                                       string[] rolesInChart)
    {
        // Collect data
        var game = _gameRoleProvider.Games.Single(m => m.PrimaryGameDiscordRoleId == primaryGameDiscordRoleId);

        var(gameMembers, roleDistribution) = _gameRoleProvider.GetGameRoleDistribution(game);
        roleDistribution = (from rd in roleDistribution
                            from ric in rolesInChart
                            where rd.Key.EndsWith(ric)
                            select new { RoleName = ric, Count = rd.Value })
                           .ToDictionary(m => m.RoleName, m => m.Count);

        // Load background and foreground image
        var backgroundImage = GetImageFromResource(barChartDrawingData.BackgroundImageName);
        var foregroundImage = GetImageFromResource(barChartDrawingData.ForegroundImageName);

        // Create image
        return(CreateImage(BarChartDrawingData.ImageWidth,
                           BarChartDrawingData.ImageHeight,
                           bitmap =>
        {
            using var canvas = new SKCanvas(bitmap);
            var arial = SKTypeface.FromFamilyName("Arial");
            var arialBold = SKTypeface.FromFamilyName("Arial", SKFontStyleWeight.Bold, SKFontStyleWidth.Normal, SKFontStyleSlant.Upright);

            // Draw background image
            canvas.DrawImage(backgroundImage, 0, 0);

            // Draw meta info
            var infoFont = new SKFont(arial, 16f);
            var infoPaint = new SKPaint(infoFont)
            {
                Color = SKColors.Black
            };
            var gameMembersText = $"Game Members: {gameMembers}";
            var createdOnText = $"Created: {DateTime.UtcNow:yyyy-MM-dd}";
            var gameMembersRequiredSize = new SKRect();
            var createdOnRequiredSize = new SKRect();
            infoPaint.MeasureText(gameMembersText, ref gameMembersRequiredSize);
            infoPaint.MeasureText(createdOnText, ref createdOnRequiredSize);
            var metaTopOffset = (BarChartDrawingData.ContentTopOffset -
                                 ((int)gameMembersRequiredSize.Height + (int)createdOnRequiredSize.Height +
                                  BarChartDrawingData.VerticalInfoTextMargin)) / 2 + 15;
            canvas.DrawText(gameMembersText,
                            BarChartDrawingData.ImageWidth - BarChartDrawingData.HorizontalInfoTextMargin - gameMembersRequiredSize.Width,
                            metaTopOffset,
                            infoFont,
                            infoPaint);
            metaTopOffset = metaTopOffset + (int)gameMembersRequiredSize.Height + BarChartDrawingData.VerticalInfoTextMargin;
            canvas.DrawText(createdOnText,
                            BarChartDrawingData.ImageWidth - BarChartDrawingData.HorizontalInfoTextMargin - createdOnRequiredSize.Width,
                            metaTopOffset,
                            infoFont,
                            infoPaint);

            // Data
            var indent = barChartDrawingData.InitialIndent;
            var labelFont = new SKFont(arialBold, barChartDrawingData.LabelFontSize);
            var amountFont = new SKFont(arialBold, 16f);
            double maxCount = roleDistribution.Values.Max();
            foreach (var(roleName, roleCount) in roleDistribution.OrderByDescending(m => m.Value).ThenBy(m => m.Key))
            {
                // Bar label
                var labelPaint = new SKPaint(labelFont)
                {
                    Color = SKColors.Black
                };
                var requiredLabelSize = new SKRect();
                labelPaint.MeasureText(roleName, ref requiredLabelSize);
                canvas.DrawText(roleName,
                                indent + (barChartDrawingData.IndentIncrement - requiredLabelSize.Width) / 2,
                                BarChartDrawingData.LabelsTopOffset,
                                labelFont,
                                labelPaint);

                // Bar
                var barHeight = (int)(roleCount / maxCount * BarChartDrawingData.BarMaxHeight);
                var topOffset = BarChartDrawingData.BarTopOffset + BarChartDrawingData.BarMaxHeight - barHeight;
                var leftOffset = indent + (barChartDrawingData.IndentIncrement - BarChartDrawingData.BarWidth) / 2;
                var rightOffset = leftOffset + BarChartDrawingData.BarWidth;
                var bottomOffset = topOffset + barHeight;
                var rect = new SKRect(leftOffset, topOffset, rightOffset, bottomOffset);
                var barColor = barChartDrawingData.BarColors[roleName];
                var barPaint = new SKPaint {
                    Color = barColor
                };
                canvas.DrawRect(rect, barPaint);

                // Amount label
                var amountPaint = new SKPaint(amountFont)
                {
                    Color = SKColors.Black
                };
                var amount = roleCount.ToString(CultureInfo.InvariantCulture);
                amountPaint.MeasureText(amount, ref requiredLabelSize);
                canvas.DrawText(amount,
                                indent + (barChartDrawingData.IndentIncrement - requiredLabelSize.Width) / 2,
                                topOffset - 10 - requiredLabelSize.Height,
                                amountFont,
                                amountPaint);

                indent += barChartDrawingData.IndentIncrement;
            }

            // Draw foreground image
            canvas.DrawImage(foregroundImage, 0, 0);
        }));
Пример #28
0
        /// <summary>Draws the X axis labels</summary>
        private void DrawLabels(SKImageInfo info, SKCanvas canvas)
        {
            // draw prime label
            if (!String.IsNullOrWhiteSpace(this.PrimeLabel))
            {
                using (SKPaint textPaint = new SKPaint()
                {
                    Color = this.PrimaryTextColor.ToSKColor()
                })
                {
                    // set the font family and style
                    this.SetFont(textPaint, this.PrimeLabelMetrics.FontSize, this.PrimeLabelAttributes);

                    textPaint.TextAlign = SKTextAlign.Center;

                    SKRect rect = new SKRect(this.Origin.X - this.MaxPrimeLabelWidth / 2.0F, this.Origin.Y - (this.PrimeLabelMetrics.Height / 2.0F),
                                             this.Origin.X + this.MaxPrimeLabelWidth / 2.0F, this.Origin.Y + (this.PrimeLabelMetrics.Height / 2.0F));

                    // show the label rect
                    if (this.LayoutGrid)
                    {
                        canvas.DrawRect(rect, new SKPaint()
                        {
                            Color = _orange, StrokeWidth = 1, Style = SKPaintStyle.Stroke
                        });
                    }

                    // draw the text centered on X
                    canvas.DrawText(this.PrimeLabel, rect.MidX, rect.Bottom - this.PrimeLabelMetrics.Descent, textPaint);
                }
            }

            // draw sub label
            if (!String.IsNullOrWhiteSpace(this.SubLabel))
            {
                using (SKPaint textPaint = new SKPaint()
                {
                    Color = this.SubTextColor.ToSKColor()
                })
                {
                    textPaint.TextAlign = SKTextAlign.Center;

                    // set the font family and style
                    this.SetFont(textPaint, this.SubLabelMetrics.FontSize, this.SubLabelAttributes);

                    // set below the prime label
                    SKRect rect = new SKRect(this.Origin.X - this.MaxPrimeLabelWidth / 2.0F, this.Origin.Y + (this.PrimeLabelMetrics.Height / 2.0F),
                                             this.Origin.X + this.MaxPrimeLabelWidth / 2.0F, this.Origin.Y + (this.PrimeLabelMetrics.Height / 2.0F) + this.SubLabelMetrics.Height);

                    if (this.LayoutGrid)
                    {
                        canvas.DrawRect(rect, new SKPaint()
                        {
                            Color = _orange, StrokeWidth = 1, Style = SKPaintStyle.Stroke
                        });
                    }

                    canvas.DrawText(this.SubLabel, rect.MidX, rect.Bottom - this.SubLabelMetrics.Descent, textPaint);
                }
            }
        }
Пример #29
0
        public void DrawText(Point geometry, Brush style)
        {
            if (style.Paint.TextOptional)
            {
                // TODO check symbol collision
                //return;
            }

            var paint       = getTextPaint(style);
            var strokePaint = getTextStrokePaint(style);
            var text        = transformText(style.Text, style);
            var allLines    = text.Split('\n');

            // detect collisions
            if (allLines.Length > 0)
            {
                var biggestLine = allLines.OrderBy(line => line.Length).Last();
                var bytes       = Encoding.UTF32.GetBytes(biggestLine);

                var width  = (int)(paint.MeasureText(bytes));
                int left   = (int)(geometry.X - width / 2);
                int top    = (int)(geometry.Y - style.Paint.TextSize / 2 * allLines.Length);
                int height = (int)(style.Paint.TextSize * allLines.Length);

                var rectangle = new Rect(left, top, width, height);
                rectangle.Inflate(5, 5);

                if (ClipOverflow)
                {
                    if (!clipRectangle.Contains(rectangle))
                    {
                        return;
                    }
                }

                if (textCollides(rectangle))
                {
                    // collision detected
                    return;
                }
                textRectangles.Add(rectangle);

                //var list = new List<Point>()
                //{
                //    rectangle.TopLeft,
                //    rectangle.TopRight,
                //    rectangle.BottomRight,
                //    rectangle.BottomLeft,
                //};

                //var brush = new Brush();
                //brush.Paint = new Paint();
                //brush.Paint.FillColor = Color.FromArgb(150, 255, 0, 0);

                //this.DrawPolygon(list, brush);
            }

            int i = 0;

            foreach (var line in allLines)
            {
                var   bytes      = Encoding.UTF32.GetBytes(line);
                float lineOffset = (float)(i * style.Paint.TextSize) - ((float)(allLines.Length) * (float)style.Paint.TextSize) / 2 + (float)style.Paint.TextSize;
                var   position   = new SKPoint((float)geometry.X + (float)(style.Paint.TextOffset.X * style.Paint.TextSize), (float)geometry.Y + (float)(style.Paint.TextOffset.Y * style.Paint.TextSize) + lineOffset);

                if (style.Paint.TextStrokeWidth != 0)
                {
                    canvas.DrawText(bytes, position, strokePaint);
                }

                canvas.DrawText(bytes, position, paint);
                i++;
            }
        }
Пример #30
0
        private void OnPaint(UIElement element, SKCanvas canvas)
        {
            canvas.Clear(SKColors.Black);

            canvas.DrawText($"Current screen: {GetType().Name} [FPS: {HipsterEngine.DeltaTime.GetFPS()}]", 10, 75,
                            new SKPaint
            {
                TextSize = 20,
                Color    = new SKColor(100, 100, 100)
            });

            canvas.DrawText($"Mouse: [{MousePosition.X}, {MousePosition.Y}]", 10, 25, new SKPaint
            {
                TextSize = 20,
                Color    = new SKColor(100, 100, 100)
            });

            var paint = new SKPaint
            {
                Style       = SKPaintStyle.Fill,
                IsAntialias = true,
                Color       = new SKColor(100, 0, 0)
            };

            for (var i = 0; i < Objects.Count; i++)
            {
                var block = Objects[i];

                //    if (block.IsVisible)
                //    {
                //        paint.Color = new SKColor(100, 0, 0);
                //        canvas.DrawRect(block.Position.X, block.Position.Y, block.Width, block.Height, paint);
                //        block.IsVisible = false;
                //    }
                //    else
                //    {

                if (typeof(Circle) == block.GetType())
                {
                    var o = (Circle)block;

                    paint.Color = new SKColor(100, 0, 0, 50);
                    canvas.DrawCircle(block.Position.X + o.Radius, block.Position.Y + o.Radius, o.Radius, paint);
                }
                else if (typeof(Block) == block.GetType())
                {
                    var o = (Block)block;

                    paint.Color = new SKColor(100, 0, 0, 50);
                    canvas.DrawRect(block.Position.X, block.Position.Y, o.Width, o.Height, paint);
                }

                //    }
            }

            //  Angle += 0.01f;
            ////   for (var i = 0; i < Lights.Count; i++)
            //   {
            //       paint.Color = Lights[i].Color;
            //       Lights[i].Angle += 3;
            //       Lights[i].AddToX((float) Math.Sin(Angle + 3) * 2);
            //       Lights[i].AddToY((float) Math.Sin(Angle + 2) * 2);

            for (var i = 0; i < SetupLight.Count; i++)
            {
                var end   = SetupLight[i].Item1;
                var light = SetupLight[i].Item2;

                var path = new SKPath();
                path.MoveTo(light.Position.X, light.Position.Y);
                path.LineTo(end.X, end.Y);
                path.Close();

                canvas.DrawPath(path, new SKPaint
                {
                    Style       = SKPaintStyle.Stroke,
                    IsAntialias = true,
                    Shader      = SKShader.CreateRadialGradient(new SKPoint(light.Position.X, light.Position.Y),
                                                                light.Radius, new SKColor[]
                    {
                        new SKColor(50, 50, 50, 100),
                        new SKColor(0, 0, 0, 100),
                    }, new float[] { 0.5f, light.Radius }, SKShaderTileMode.Clamp),
                    Color = new SKColor(200, 200, 200)
                });
            }


            //    }

            HipsterEngine.Surface.Canvas.Save();
            HipsterEngine.Particles.Draw(HipsterEngine.Surface.Canvas.GetSkiaCanvas());
            HipsterEngine.Surface.Canvas.Restore();
        }