Exemplo n.º 1
0
        private void SpawnWave(ArtemisLed led, SKPoint relativeLedPosition)
        {
            lock (_waves)
            {
                List <KeypressWave> existing = _waves.Where(w => w.Led == led).ToList();
                if (existing.Any())
                {
                    foreach (KeypressWave keypressWave in existing)
                    {
                        keypressWave.Shrink = false;
                        keypressWave.Size   = Math.Max(keypressWave.Size, 0);
                    }

                    return;
                }

                KeypressWave wave = new KeypressWave(
                    led,
                    relativeLedPosition,
                    new SKPaint {
                    Color = SKColor.FromHsv(_rand.Next(0, 360), 100, 100)
                }
                    );
                _waves.Add(wave);
            }
        }
Exemplo n.º 2
0
 private void UpdatePaint()
 {
     if (_brush.Properties.ColorMode.CurrentValue == ColorType.Random && Paint == null)
     {
         Paint = new SKPaint {
             Color = SKColor.FromHsv(_brush.Rand.Next(0, 360), 100, 100)
         }
     }
     ;
     else if (_brush.Properties.ColorMode.CurrentValue == ColorType.Solid)
     {
         Paint = new SKPaint {
             Color = _brush.Properties.Color.CurrentValue
         }
     }
     ;
     else if (_brush.Properties.ColorMode.CurrentValue == ColorType.Gradient)
     {
         Paint = new SKPaint
         {
             Shader = SKShader.CreateRadialGradient(
                 Position,
                 Size,
                 _brush.Properties.Colors.BaseValue.GetColorsArray(),
                 _brush.Properties.Colors.BaseValue.GetPositionsArray(),
                 SKShaderTileMode.Clamp
                 )
         }
     }
     ;
 }
Exemplo n.º 3
0
        //internal static float[] ColorToHSV(int originalColor)
        //{
        //    float[] hsv = new float[3];
        //    SKColor.RGBToHSV(Color.GetRedComponent(originalColor), Color.GetGreenComponent(originalColor), Color.GetBlueComponent(originalColor), hsv);
        //    return hsv;
        //}

        //public static int colorByChangingHue(int originalColor, float newHue)
        //{
        //    float[] hsv = ColorToHSV(originalColor);
        //    hsv[0] = newHue;
        //    return Color.HSVToColor(Color.GetAlphaComponent(originalColor), hsv);
        //}

        public static SKColor colorByChangingSaturation(SKColor originalColor, float newSaturation)
        {
            float h, s, v;

            originalColor.ToHsv(out h, out s, out v);
            return(SKColor.FromHsv(h, newSaturation, v));
        }
        private void OnHsvCanvasViewPaintSurface(object sender, SkiaSharp.Views.Forms.SKPaintSurfaceEventArgs e)
        {
            SKColor color = SKColor.FromHsv((float)hueSlider.Value, (float)saturationSlider.Value, (float)valueSlider.Value);

            e.Surface.Canvas.Clear(color);
            hslLabel.Text = String.Format("RGB = {0:X2}-{1:X2}-{2:X2} ", color.Red, color.Green, color.Blue);
        }
Exemplo n.º 5
0
    public void HsvColor()
    {
        using var img = GenericVisualizer.RenderPalette(
                  new Size(10, 10),
                  pos => SKColor.FromHsv(0, 100 * (pos.X / 10f), 100 * (pos.Y / 10f)),
                  scale: 20);

        Save(img, "HSV with Saturation x Value");
    }
Exemplo n.º 6
0
        public override IRender Render(float dt)
        {
            _offset = (_offset + _speed * dt) % 360;
            _render.Map((x, y) =>
            {
                float hue = ((float)x / Width * 360f * _scale + _offset) % 360;
                return(SKColor.FromHsv(hue, 100, 100));
            });

            return(_render);
        }
Exemplo n.º 7
0
        void DrawRange(SKCanvas canvas, int width, int height, float degreesOffset, int steps,
                       Func <int, int, float> calcStepSide, float value, bool drawColorValuesAsText = false)
        {
            var degreesStep = 360f / steps;
            var halfWidth   = width / 2f;
            var halfHeight  = height / 2f;
            var stepSide    = calcStepSide(width, height);
            var scale       = width / (float)canvasView.Width;
            var textBrush   = new SKPaint
            {
                IsAntialias = true,
                Style       = SKPaintStyle.Fill,
                Color       = SKColors.White,
                TextSize    = 10 * scale
            };
            var arcRect = new SKRect(halfWidth - stepSide, halfHeight - stepSide,
                                     halfWidth + stepSide, halfHeight + stepSide);

            for (var i = 0; i < steps; i++)
            {
                var degrees           = i * degreesStep;
                var degreesWithOffset = degrees + degreesOffset;
                var brush             = new SKPaint
                {
                    IsAntialias = true,
                    Style       = SKPaintStyle.Fill,
                    Color       = hslOrHsvEnabled ?
                                  SKColor.FromHsl(degrees, 100, value, 255) :
                                  SKColor.FromHsv(degrees, 100, value, 255)
                };

                canvas.RotateDegrees(degreesWithOffset, halfWidth, halfHeight);
                using (var path = new SKPath())
                {
                    path.MoveTo(halfWidth, halfHeight);
                    //path.LineTo(halfWidth, halfHeight - stepSide);
                    //path.LineTo(halfWidth + (float)Math.Tan((Math.PI / 180) * degreesStep) * stepSide, halfHeight - stepSide);
                    path.ArcTo(arcRect, 270, degreesStep, false);
                    path.Close();
                    canvas.DrawPath(path, brush);
                }

                if (drawColorValuesAsText)
                {
                    var textX = halfWidth;
                    var textY = halfHeight - 3 * (stepSide / 4);
                    canvas.DrawText(brush.Color.ToString(), textX, textY, textBrush);
                }

                canvas.RotateDegrees(-degreesWithOffset, halfWidth, halfHeight);
            }
        }
Exemplo n.º 8
0
        /// <summary>
        /// Reapplies the color mix properties to take into account the
        /// effect of any connected properties.
        /// </summary>
        private void RemixColor()
        {
            // Update connected properties
            EvaluateConnectedProperties();

            // Get color values
            var h = (AdjustsHue) ? HueAdjustment : Hue;
            var s = (AdjustsSaturation) ? SaturationAdjustment : Saturation;
            var v = (AdjustsBrightness) ? BrightnessAdjustment : Brightness;
            var a = (AdjustsAlpha) ? AlphaAdjustment : Alpha;

            // Blend new color
            _color = SKColor.FromHsv(h, s, v, (byte)a);
        }
Exemplo n.º 9
0
        private void UpdatePaint()
        {
            if (_brush.Properties.ColorMode.CurrentValue == ColorType.Random && Paint == null)
            {
                Paint = new SKPaint {
                    Color = SKColor.FromHsv(_brush.Rand.Next(0, 360), 100, 100)
                };
            }
            else if (_brush.Properties.ColorMode.CurrentValue == ColorType.Solid)
            {
                Paint?.Dispose();
                Paint = new SKPaint {
                    Color = _brush.Properties.Color.CurrentValue
                };
            }
            else if (_brush.Properties.ColorMode.CurrentValue == ColorType.Gradient)
            {
                Paint?.Dispose();
                Paint = new SKPaint
                {
                    Shader = SKShader.CreateRadialGradient(
                        Position,
                        Size,
                        _brush.Properties.Colors.BaseValue.GetColorsArray(),
                        _brush.Properties.Colors.BaseValue.GetPositionsArray(),
                        SKShaderTileMode.Clamp
                        )
                };
            }
            else if (_brush.Properties.ColorMode.CurrentValue == ColorType.ColorChange)
            {
                Paint?.Dispose();
                Paint = new SKPaint {
                    Color = _brush.Properties.Colors.CurrentValue.GetColor(_progress)
                };
            }

            // Add fade away effect
            if (_brush.Properties.RippleFadeAway != RippleFadeOutMode.None)
            {
                Paint.Color = Paint.Color.WithAlpha((byte)(255 * Easings.Interpolate(1 - _progress, (Easings.Functions)_brush.Properties.RippleFadeAway.BaseValue)));
            }

            // Set ripple size
            Paint.Style       = SKPaintStyle.Stroke;
            Paint.IsAntialias = true;
            Paint.StrokeWidth = _brush.Properties.RippleWidth.CurrentValue;
        }
        public AaronPenneButterfly(int width, int height)
        {
            w = width;
            h = height;
            // # Sets color space to Hue Saturation Brightness with max values of HSB respectively
            // colorMode(HSB, 360, 100, 100, 100)
            SKColorFilter colorMode = SKColorFilter.CreateBlendMode(SKColor.FromHsv(360, 100, 100, 100), SKBlendMode.Hue);

            paint = new SKPaint {
                IsAntialias = true,
                Style       = SKPaintStyle.Stroke,
                StrokeJoin  = SKStrokeJoin.Round,
                BlendMode   = SKBlendMode.Multiply,
                //ColorFilter = colorMode
            };
        }
Exemplo n.º 11
0
        public ColorBrush(Layer layer, ColorBrushSettings settings, LayerBrushDescriptor descriptor) : base(layer, settings, descriptor)
        {
            Settings = settings;

            _testColors = new List <SKColor>();
            for (var i = 0; i < 9; i++)
            {
                if (i != 8)
                {
                    _testColors.Add(SKColor.FromHsv(i * 32, 100, 100));
                }
                else
                {
                    _testColors.Add(SKColor.FromHsv(0, 100, 100));
                }
            }

            CreateShader();
            Layer.RenderPropertiesUpdated += (sender, args) => CreateShader();
            Settings.PropertyChanged      += (sender, args) => CreateShader();
        }
Exemplo n.º 12
0
        public static void DrawApproachCircle(SKCanvas canvas, int gameTime, OsuHitObject obj)
        {
            double t0             = obj.StartTime - obj.TimePreempt;
            double t1             = t0 + obj.TimeFadeIn;
            double fadeInProgress = (gameTime - t0) / (t1 - t0);
            double transparency   =
                (gameTime < t0) ? 0 :
                (gameTime < t1) ? 255 * fadeInProgress
                                : 255;
            float approachProgress    = (float)((obj.StartTime - gameTime) / obj.TimePreempt);
            float approachCircleScale = 1.0f + approachProgress * (approachCircleMaxScale - 1.0f);
            var   approachCircleStyle = new SKPaint
            {
                IsAntialias = true,
                IsStroke    = true,
                Color       = SKColor.FromHsv(0, 0, 80, (byte)transparency),
                StrokeWidth = 4
            };

            canvas.DrawCircle(obj.StackedPosition.X + offsetX, obj.StackedPosition.Y + offsetY, (approachCircleScale * (float)obj.Radius) / 2.0f, approachCircleStyle);
            return;
        }
Exemplo n.º 13
0
 private void UpdatePaint(bool respawn)
 {
     if (_brush.Properties.ColorMode.CurrentValue == ColorType.Random && (Paint == null || respawn))
     {
         Paint = new SKPaint {
             Color = SKColor.FromHsv(_brush.Rand.Next(0, 360), 100, 100)
         }
     }
     ;
     else if (_brush.Properties.ColorMode.CurrentValue == ColorType.Solid)
     {
         Paint = new SKPaint {
             Color = _brush.Properties.Color.CurrentValue
         }
     }
     ;
     else if (_brush.Properties.ColorMode.CurrentValue == ColorType.Gradient)
     {
         Paint = new SKPaint {
             Color = _brush.Properties.Colors.CurrentValue.GetColor((float)Progress)
         }
     }
     ;
 }
Exemplo n.º 14
0
        // Implement drawing cycle.
        void OnCanvasViewPaintSurface(object sender, SKPaintSurfaceEventArgs args)
        {
            SKImageInfo info    = args.Info;
            SKSurface   surface = args.Surface;
            SKCanvas    canvas  = surface.Canvas;

            //canvas.Clear();

            using (SKPaint fillPaint = new SKPaint {
                Style = SKPaintStyle.Stroke,
                Color = SKColor.FromHsv(hue, 100, 100),
                StrokeWidth = 10
            })
            {
                // Translate to center of canvas
                canvas.Translate(info.Width / 2, info.Height / 2);

                for (int angle = 0; angle < 360; angle += 45)
                {
                    canvas.Save();

                    // Rotate around center of canvas
                    canvas.RotateDegrees(revolveDegrees + angle);
                    // Translate horizontally
                    float madLad = Math.Min(info.Width, info.Height) / 3;
                    canvas.Translate(madLad * radius, 0);
                    // Rotate around center of object
                    canvas.RotateDegrees(rotateDegrees);
                    // Draw a square
                    float apothem = 30 + angle * 0.1f;
                    canvas.DrawRect(new SKRect(-apothem, -apothem, apothem, apothem), fillPaint);

                    canvas.Restore();
                }
            }
        }
Exemplo n.º 15
0
        public void ColorRgbToHsv()
        {
            var tuples = new List <ToOtherColor> {
                new ToOtherColor(new SKColor(000, 000, 000), new SKOtherColor(000f, 000.0f, 000.0f), "Black"),
                new ToOtherColor(new SKColor(255, 000, 000), new SKOtherColor(000f, 100.0f, 100.0f), "Red"),
                new ToOtherColor(new SKColor(255, 255, 000), new SKOtherColor(060f, 100.0f, 100.0f), "Yellow"),
                new ToOtherColor(new SKColor(255, 255, 255), new SKOtherColor(000f, 000.0f, 100.0f), "White"),
                new ToOtherColor(new SKColor(128, 128, 128), new SKOtherColor(000f, 000.0f, 050.2f), "Gray"),
                new ToOtherColor(new SKColor(128, 128, 000), new SKOtherColor(060f, 100.0f, 050.2f), "Olive"),
                new ToOtherColor(new SKColor(000, 128, 000), new SKOtherColor(120f, 100.0f, 050.2f), "Green"),
                new ToOtherColor(new SKColor(000, 000, 128), new SKOtherColor(240f, 100.0f, 050.2f), "Navy"),
            };

            foreach (var item in tuples)
            {
                // values
                SKColor      rgb   = item.Item1;
                SKOtherColor other = item.Item2;

                // to HSV
                float h, s, v;
                rgb.ToHsv(out h, out s, out v);

                Assert.AreEqual(other.Item1, h, EPSILON, item.Item3 + " H");
                Assert.AreEqual(other.Item2, s, EPSILON, item.Item3 + " S");
                Assert.AreEqual(other.Item3, v, EPSILON, item.Item3 + " V");

                // to RGB
                SKColor back = SKColor.FromHsv(other.Item1, other.Item2, other.Item3);

                Assert.AreEqual(rgb.Red, back.Red, item.Item3 + " R");
                Assert.AreEqual(rgb.Green, back.Green, item.Item3 + " G");
                Assert.AreEqual(rgb.Blue, back.Blue, item.Item3 + " B");
                Assert.AreEqual(rgb.Alpha, back.Alpha, item.Item3 + " A");
            }
        }
Exemplo n.º 16
0
 /// <summary>
 /// Creates a Color from its HSV representation.
 ///
 /// RGB conversion done according to:
 /// https://en.wikipedia.org/wiki/HSL_and_HSV#From_HSV
 /// </summary>
 /// <param name="H">Hue H ∈ [0°, 360°).</param>
 /// <param name="S">Saturation SHSL ∈ [0, 1].</param>
 /// <param name="V">Value V ∈ [0, 1].</param>
 /// <param name="A">Alpha A ∈ [0, 255].</param>
 /// <returns>Color</returns>
 public static SKColor ToColorHSV(double H, double S, double V, byte A)
 {
     return(SKColor.FromHsv((float)H, (float)(S * 255), (float)(V * 255), A));
 }
Exemplo n.º 17
0
 private void TimedUpdate(double deltaTime)
 {
     DataModel.TestColorA = SKColor.FromHsv(_rand.Next(0, 360), 100, 100);
     DataModel.TestColorB = SKColor.FromHsv(_rand.Next(0, 360), 100, 100);
 }
Exemplo n.º 18
0
        private void UpdatePaint()
        {
            if (_brush.Properties.ColorMode.CurrentValue == ColorType.Random && !_colorFixed)
            {
                _colorFixed  = true;
                _rippleColor = SKColor.FromHsv(_brush.Rand.Next(0, 360), 100, 100);
            }
            else if (_brush.Properties.ColorMode.CurrentValue == ColorType.ColorSet && !_colorFixed)
            {
                _colorFixed  = true;
                _rippleColor = _brush.Properties.Colors.CurrentValue.GetColor((float)_random.NextDouble());
            }
            else if (_brush.Properties.ColorMode.CurrentValue == ColorType.Solid && !_colorFixed)
            {
                _colorFixed  = true;
                _rippleColor = _brush.Properties.Color.CurrentValue;
            }
            else if (_brush.Properties.ColorMode.CurrentValue == ColorType.Gradient)
            {
                _paint?.Shader?.Dispose();
                _paint.Shader = SKShader.CreateRadialGradient
                                (
                    Position,
                    _brush.Properties.RippleWidth,
                    _brush.Properties.Colors.BaseValue.GetColorsArray(),
                    _brush.Properties.Colors.BaseValue.GetPositionsArray(),
                    SKShaderTileMode.Repeat
                                );
            }
            else if (_brush.Properties.ColorMode.CurrentValue == ColorType.ColorPathChange)
            {
                _rippleColor = _brush.Properties.Colors.CurrentValue.GetColor(_progress);
            }

            byte alpha = 255;

            _paint.Color = _rippleColor;

            // Add fade away effect
            if (_brush.Properties.RippleFadeAway != RippleFadeOutMode.None)
            {
                alpha = (byte)(255d * Easings.Interpolate(1d - _progress, (Easings.Functions)_brush.Properties.RippleFadeAway.CurrentValue));
            }

            alpha = (byte)((_rippleColor.Alpha / 255f) * alpha);
            SKColor trailColor;

            // If we have to paint a trail
            if (_brush.Properties.RippleTrail)
            {
                // Moved trail color calculation here to avoid extra overhead when trail is not enabled
                trailColor = _brush.Properties.ColorMode.CurrentValue switch
                {
                    // If gradient is used, calculate the inner color to a given position.
                    ColorType.Gradient => _brush.Properties.Colors.CurrentValue.GetColor((Size - _brush.Properties.RippleWidth / 2f) % _brush.Properties.RippleWidth / _brush.Properties.RippleWidth),
                    // If not gradient, we can just copy the color of the ripple Paint.
                    _ => _paint.Color
                };

                // Dispose before to create a new one. Thanks for the lesson.
                _trailPaint?.Shader?.Dispose();
                _trailPaint.Shader = SKShader.CreateRadialGradient
                                     (
                    Position,
                    Size,
                    // Trail is simply a gradient from full inner ripple color to the same color but with alpha 0. Just an illusion :D
                    new[] { trailColor.WithAlpha(0), trailColor.WithAlpha(alpha) },
                    new[] { 0f, 1f },
                    SKShaderTileMode.Clamp
                                     );
            }

            // Set ripple size and final color alpha
            _paint.Color = _paint.Color.WithAlpha(alpha);

            // SkiaSharp shapes doesn't support inner stroke so it will cause a weird empty circle if stroke
            // width is greater than the double of the size of a shape. This operation will produce perfect ripples
            _paint.StrokeWidth = Math.Min(_brush.Properties.RippleWidth.CurrentValue, Size * 2f);
        }
Exemplo n.º 19
0
        public static void DrawSlider(SKCanvas canvas, int gameTime, Slider slider, double velocity)
        {
            double slideDuration      = slider.Path.Distance / velocity;
            double totalSlideDuration = slideDuration * (slider.RepeatCount + 1);
            // t0 => slider is starting to fade in
            // t1 => slider is now fully visible
            // t2 => slider has started sliding
            // t3 => slider has finished sliding
            // t4 => slider is no longer visible
            double t0 = slider.StartTime - slider.TimePreempt;
            double t1 = t0 + slider.TimeFadeIn;
            double t2 = slider.StartTime;
            double t3 = t2 + totalSlideDuration;
            double t4 = t3 + 250;

            // progress 0 -> 1
            double fadeInProgress = (gameTime - t0) / (t1 - t0);

            ////////////////////////////////
            // draw slider body
            ////////////////////////////////
            double bodyFadeOutProgress = (gameTime - t3) / (t4 - t3);
            double bodyTransparency    =
                (gameTime < t0) ? 0 :
                (gameTime < t1) ? 255 * fadeInProgress :
                (gameTime < t3) ? 255 :
                (gameTime < t3 + 250) ? 255 * (1 - bodyFadeOutProgress) :
                0;

            var sliderBorderStyle = new SKPaint
            {
                Style       = SKPaintStyle.Stroke,
                StrokeCap   = SKStrokeCap.Round,
                IsAntialias = true,
                Color       = new SKColor(98, 114, 164, (byte)(0.5f * bodyTransparency)),
                StrokeWidth = 0.95f * (float)slider.Radius
            };
            var sliderBodyStyle = new SKPaint
            {
                Style       = SKPaintStyle.Stroke,
                StrokeCap   = SKStrokeCap.Round,
                IsAntialias = true,
                Color       = new SKColor(0, 0, 0, (byte)(0.4f * bodyTransparency)),
                StrokeWidth = 0.8f * (float)slider.Radius
            };
            var sliderPath = new List <osuTK.Vector2>();

            slider.Path.GetPathToProgress(sliderPath, 0, 1);
            var drawPath = new SKPath();

            foreach (var pathPoint in sliderPath)
            {
                var absPoint = new SKPoint(slider.StackedPosition.X + pathPoint.X + offsetX, slider.StackedPosition.Y + pathPoint.Y + offsetY);
                if (drawPath.PointCount == 0)
                {
                    drawPath.MoveTo(absPoint);
                }
                else
                {
                    drawPath.LineTo(absPoint);
                }
            }
            canvas.DrawPath(drawPath, sliderBorderStyle);
            canvas.DrawPath(drawPath, sliderBodyStyle);

            ////////////////////////////////
            // draw slider follow circle
            ////////////////////////////////
            if (gameTime > slider.StartTime && gameTime < slider.StartTime + totalSlideDuration)
            {
                int    slideNumber        = (int)((gameTime - slider.StartTime) / slideDuration);
                double relativeSliderTime = gameTime - slider.StartTime;
                while (relativeSliderTime > slideDuration)
                {
                    relativeSliderTime -= slideDuration;
                }
                double progress =
                    (slideNumber % 2 == 0) ? relativeSliderTime / slideDuration
                                           : 1 - relativeSliderTime / slideDuration;
                var followCirclePosition = slider.Position + slider.Path.PositionAt(progress);
                var followCircleStyle    = new SKPaint
                {
                    IsAntialias = true,
                    IsStroke    = true,
                    Color       = SKColor.FromHsv(0, 0, 80),
                    StrokeWidth = 4
                };
                canvas.DrawCircle(followCirclePosition.X + offsetX, followCirclePosition.Y + offsetY, 0.85f * (float)slider.Radius / 2.0f, followCircleStyle);
            }

            ////////////////////////////////
            // draw slider head
            ////////////////////////////////
            double headFadeOutProgress =
                (gameTime < t2 + 250.0) ? (gameTime - t2) / 250.0
                                        : 1.0f;
            double headTransparency =
                (gameTime < t0) ? 0 :
                (gameTime < t1) ? 255 * fadeInProgress :
                (gameTime < t2) ? 255 :
                (gameTime < t2 + 250) ? 255 * (1 - headFadeOutProgress) :
                0;
            double headScale =
                (gameTime < t2) ? 1.0 :
                1.0 + 0.3 * Math.Sqrt(Math.Sin(Math.PI * headFadeOutProgress / 2.0));

            DrawCircleImage(canvas, slider.StackedPosition, (float)(headScale * slider.Radius) / 2.0f, HitCircleOverlayBitmap, (byte)headTransparency);
            //var circleStyle = new SKPaint
            //{
            //    IsAntialias = true,
            //    IsStroke = true,
            //    Color = SKColor.FromHsv(0, 0, 80, (byte)headTransparency),
            //    StrokeWidth = 6
            //};
            //canvas.DrawCircle(slider.StackedPosition.X, slider.StackedPosition.Y, (float)(headScale * slider.Radius) / 2.0f, circleStyle);
        }
Exemplo n.º 20
0
        private void UpdatePaint()
        {
            if (_brush.Properties.ColorMode.CurrentValue == ColorType.Random && Paint == null)
            {
                Paint = new SKPaint {
                    Color = SKColor.FromHsv(_brush.Rand.Next(0, 360), 100, 100)
                };
            }
            else if (_brush.Properties.ColorMode.CurrentValue == ColorType.Solid)
            {
                Paint?.Dispose();
                Paint = new SKPaint {
                    Color = _brush.Properties.Color.CurrentValue
                };
            }
            else if (_brush.Properties.ColorMode.CurrentValue == ColorType.Gradient)
            {
                Paint?.Dispose();
                Paint = new SKPaint
                {
                    Shader = SKShader.CreateRadialGradient(
                        Position,
                        _brush.Properties.RippleWidth,
                        _brush.Properties.Colors.BaseValue.GetColorsArray(),
                        _brush.Properties.Colors.BaseValue.GetPositionsArray(),
                        // Changed from Clamp to repeat. It just looks a lot better this way.
                        // Repeat will need a color position calculation by the way to get the inner ripple color ir order to paint the Trail.
                        SKShaderTileMode.Repeat
                        )
                };
            }
            else if (_brush.Properties.ColorMode.CurrentValue == ColorType.ColorChange)
            {
                Paint?.Dispose();
                Paint = new SKPaint {
                    Color = _brush.Properties.Colors.CurrentValue.GetColor(_progress)
                };
            }

            byte alpha = 255;

            // Add fade away effect
            if (_brush.Properties.RippleFadeAway != RippleFadeOutMode.None)
            {
                alpha = (byte)(255d * Easings.Interpolate(1f - _progress, (Easings.Functions)_brush.Properties.RippleFadeAway.CurrentValue));
            }

            // If we have to paint a trail
            if (_brush.Properties.RippleTrail)
            {
                // Moved trail color calculation here to avoid extra overhead when trail is not enabled
                _trailColor = _brush.Properties.ColorMode.CurrentValue switch
                {
                    // If gradient is used, calculate the inner color to a given position.
                    ColorType.Gradient => _brush.Properties.Colors.CurrentValue.GetColor((Size - _brush.Properties.RippleWidth / 2f) % _brush.Properties.RippleWidth / _brush.Properties.RippleWidth),
                    // If not gradient, we can just copy the color of the ripple Paint.
                    _ => Paint.Color
                };

                // Dispose before to create a new one. Thanks for the lesson.
                _trailPaint?.Dispose();
                _trailPaint = new SKPaint
                {
                    Shader = SKShader.CreateRadialGradient(
                        Position,
                        Size,
                        // Trail is simply a gradient from full inner ripple color to the same color but with alpha 0. Just an illution :D
                        new[] { _trailColor.WithAlpha(0), _trailColor.WithAlpha(alpha) },
                        new[] { 0f, 1f },
                        SKShaderTileMode.Clamp
                        )
                };
                _trailPaint.Style = SKPaintStyle.Fill;
            }

            // Set ripple size and final color alpha
            Paint.Color       = Paint.Color.WithAlpha(alpha);
            Paint.Style       = SKPaintStyle.Stroke;
            Paint.StrokeWidth = _brush.Properties.RippleWidth.CurrentValue;
        }
Exemplo n.º 21
0
        protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate(bundle);
            SetContentView(Resource.Layout.MainView);
            var skia = FindViewById <SKCanvasView>(Resource.Id.canvasView);

            skia.PaintSurface += (sender, e) => //событие, использующееся для отрисовки на Canvas
            {
                var info    = e.Info;           //разная инфа о рабочей области: ширина, высота, итд
                var surface = e.Surface;        // доступ к рабочей плоскости
                var canvas  = surface.Canvas;   //доступ к canvas'у
                //определение начала и конца оси X
                var xCoordStart = new Point(info.Width / 20, info.Height - (info.Height / 3));
                var xCoordEnd   = new Point(info.Width - (info.Width / 20), info.Height - (info.Height / 3));
                //определение начала и конца оси Y
                var yCoordStart = new Point(info.Width / 20, info.Height - (info.Height / 3));
                var yCoordEnd   = new Point(info.Width / 20, info.Height / 95);

                canvas.Clear(SKColors.White);
                //экземпляры класса SKPaint, которыми мы рисуем
                //ось
                var axisBrush = new SKPaint
                {
                    Style       = SKPaintStyle.Stroke,
                    StrokeWidth = 8,
                    Color       = SKColor.FromHsv(0, 0, 75),
                };
                //текст лейблов
                var textBrush = new SKPaint
                {
                    Color        = SKColors.SlateGray,
                    StrokeWidth  = 2,
                    TextSize     = 45f,
                    FakeBoldText = true,
                };
                //текст на зеленом окошечке
                var messageBrush = new SKPaint
                {
                    Color        = SKColors.White,
                    StrokeWidth  = 2,
                    TextSize     = 55,
                    FakeBoldText = true
                };
                //линия графика
                var chartBrush = new SKPaint
                {
                    Style       = SKPaintStyle.Stroke,
                    Color       = SKColors.Goldenrod,
                    StrokeWidth = 10
                };
                //делаем сереньким фон
                canvas.DrawColor(SKColor.FromHsv(0, 0, 90));
                //Внимание! Код ниже представляет собой набор из хаотически добавленных функций, в которых
                //коэффициенты расставлены методом научного тыка, а решение до безобразия неоптимизировано.
                //в дальнейшем числа, встречающиеся более-менее часто, будут вынесены как константы.
                while (i < 7) //рисуем 7 горизонтальных линий
                {
                    canvas.DrawLine(xCoordStart.X, xCoordStart.Y - i * 150, xCoordEnd.X, xCoordEnd.Y - i++ *150, axisBrush);
                }

                canvas.DrawText("MARCH", xCoordStart.X, xCoordStart.Y + 80, textBrush);
                for (int k = 0; k < 6; k++)  //рисуем лейблы по X
                {
                    canvas.DrawText((k + 12).ToString(), 200 + yCoordStart.X + 170 * k, yCoordStart.Y + 80, textBrush);
                }
                for (int k = 1; k < 7; k++) //рисуем лейблы по Y
                {
                    canvas.DrawText((20 * k).ToString(), xCoordStart.X + 20, xCoordStart.Y - k * 150 + 60, textBrush);
                }

                canvas.DrawPoints(SKPointMode.Polygon, points, chartBrush);
                for (int j = 1; j < points.Length; j++)
                {
                    canvas.DrawCircle(points[j].X, points[j].Y, 18, new SKPaint {
                        StrokeWidth = 10, Color = SKColors.Goldenrod, Style = SKPaintStyle.Stroke
                    });
                    canvas.DrawCircle(points[j].X, points[j].Y, 13, new SKPaint {
                        Color = SKColors.White, Style = SKPaintStyle.Fill
                    });
                }
                canvas.DrawCircle(points[2].X, points[2].Y, 18, new SKPaint {
                    StrokeWidth = 10, Color = SKColors.White, Style = SKPaintStyle.Stroke
                });
                canvas.DrawCircle(points[2].X, points[2].Y, 13, new SKPaint {
                    Color = SKColors.Green, Style = SKPaintStyle.Fill
                });
                SKRect rect = new SKRect
                {
                    Size     = new SKSize(500, 250),
                    Location = new SKPoint(points[2].X - 250, points[2].Y - 300)
                };
                canvas.DrawRoundRect(rect, 10, 10, new SKPaint {
                    Style = SKPaintStyle.Fill, Color = SKColors.Green
                });
                SKPath triangle = new SKPath();
                triangle.MoveTo(points[2].X, points[2].Y - 25);
                triangle.LineTo(points[2].X - 35, points[2].Y - 50);

                triangle.LineTo(points[2].X + 35, points[2].Y - 50);
                triangle.LineTo(points[2].X, points[2].Y - 25);
                triangle.Close();

                canvas.DrawPath(triangle, new SKPaint {
                    Color = SKColors.Green, Style = SKPaintStyle.Fill
                });
                canvas.DrawText("100 pts", rect.Location.X + 150, rect.Location.Y + 80, messageBrush);
                messageBrush.FakeBoldText = false;
                canvas.DrawText("John Douglas", rect.Location.X + 90, rect.Location.Y + 150, messageBrush);
                //canvas.DrawLine(yCoordStart.X, yCoordStart.Y, yCoordEnd.X, yCoordEnd.Y, axisBrush);
            };
        }