public void UpdateColor()
        {
            RGBColor rgb = HueLight.ToRGBColor();

            SolidColor = new SKColor(ClampToByte(rgb.R * 255), ClampToByte(rgb.G * 255), ClampToByte(rgb.B * 255));
            Color      = SolidColor.WithAlpha(Brightness);
        }
Beispiel #2
0
        private static void DrawEllipse(SKCanvas canvas, SKColor color, TmxMap tmxMap, TmxObjectEllipse tmxEllipse)
        {
            SKRect  rc     = new SKRect(0, 0, tmxEllipse.Size.Width, tmxEllipse.Size.Height);
            SKColor stroke = color;
            SKColor fill   = color.WithAlpha(128);

            using (SKPaint paint = new SKPaint())
                using (SKPath path = new SKPath())
                {
                    if (tmxMap.Orientation == TmxMap.MapOrientation.Isometric)
                    {
                        // Circles and ellipses not supported in Insometric mode
                        stroke = SKColors.Black;
                        fill   = SKColors.Red;
                        Logger.WriteWarning("Circles/Ellipses not supported in isometric mode: {0}", tmxEllipse.GetNonEmptyName());
                    }
                    else if (!tmxEllipse.IsCircle())
                    {
                        stroke = SKColors.Black;
                        fill   = SKColors.Red;
                        Logger.WriteWarning("Object is an ellipse and will be ignored (only circles supported): {0}", tmxEllipse.GetNonEmptyName());
                    }
                    path.AddOval(rc);

                    paint.Style = SKPaintStyle.Fill;
                    paint.Color = fill;
                    canvas.DrawPath(path, paint);

                    paint.Style       = SKPaintStyle.Stroke;
                    paint.StrokeWidth = StrokeWidthThick;
                    paint.Color       = stroke;
                    canvas.DrawPath(path, paint);
                }
        }
Beispiel #3
0
        private void RenderColorPickerOverlay(object?sender, FrameRenderingEventArgs e)
        {
            if (_mustRenderOverlay)
            {
                _overlayOpacity += 0.2f;
            }
            else
            {
                _overlayOpacity -= 0.2f;
            }

            if (_overlayOpacity <= 0f)
            {
                _coreService.FrameRendering -= RenderColorPickerOverlay;
                return;
            }

            if (_overlayOpacity > 1f)
            {
                _overlayOpacity = 1f;
            }

            using SKPaint overlayPaint = new() { Color = new SKColor(0, 0, 0, (byte)(255 * _overlayOpacity)) };
            overlayPaint.Color         = _overlayColor.WithAlpha((byte)(_overlayColor.Alpha * _overlayOpacity));
            e.Canvas.DrawRect(0, 0, e.Canvas.LocalClipBounds.Width, e.Canvas.LocalClipBounds.Height, overlayPaint);
        }
    }
Beispiel #4
0
 private void DrawVerseLabel(SKCanvas canvas, SKTypeface typeface, float fontSize, SKColor color, string text, float x, float y, float verseOpacity)
 {
     using (var paint = CreatePaint(typeface, fontSize, color.WithAlpha((byte)(verseOpacity * 255))))
     {
         SafeDrawText(canvas, text, x, y, paint);
     }
 }
        /// <summary>
        /// Draws the provided path in filled mode with the provided color and alpha.
        /// Special thanks to Angelo Suzuki (https://github.com/tinsukE) for this.
        protected void DrawFilledPath(SKCanvas c, SKPath filledPath, SKColor fillColor, byte fillAlpha)
        {
            int save = c.Save();

            c.ClipPath(filledPath);
            c.DrawColor(fillColor.WithAlpha(fillAlpha), SKBlendMode.SrcOver);
            c.RestoreToCount(save);
        }
Beispiel #6
0
        public SKColor Calculate(float a, float b, float c, float?alpha = null)
        {
            // A, B and C represent a red, green and blue components of a calibrated
            // rgb space.
            var A = AdjustToRange(0, 1, a);
            var B = AdjustToRange(0, 1, b);
            var C = AdjustToRange(0, 1, c);

            // A <---> AGR in the spec
            // B <---> BGG in the spec
            // C <---> CGB in the spec
            var AGR = Math.Pow(A, GR);
            var BGG = Math.Pow(B, GG);
            var CGB = Math.Pow(C, GB);

            // Computes intermediate variables L, M, N as per spec.
            // To decode X, Y, Z values map L, M, N directly to them.
            var X = MXA * AGR + MXB * BGG + MXC * CGB;
            var Y = MYA * AGR + MYB * BGG + MYC * CGB;
            var Z = MZA * AGR + MZB * BGG + MZC * CGB;

            // The following calculations are based on this document:
            // http://www.adobe.com/content/dam/Adobe/en/devnet/photoshop/sdk/
            // AdobeBPC.pdf.
            var XYZ = new float[3];

            XYZ[0] = (float)X;
            XYZ[1] = (float)Y;
            XYZ[2] = (float)Z;
            var XYZ_Flat = new float[3];

            NormalizeWhitePointToFlat(whitePoint, XYZ, XYZ_Flat);

            var XYZ_Black = new float[3];

            CompensateBlackPoint(blackPoint, XYZ_Flat, XYZ_Black);

            var XYZ_D65 = new float[3];

            NormalizeWhitePointToD65(FLAT_WHITEPOINT_MATRIX, XYZ_Black, XYZ_D65);

            var SRGB = new float[3];

            MatrixProduct(SRGB_D65_XYZ_TO_RGB_MATRIX, XYZ_D65, SRGB);

            // Convert the values to rgb range [0, 255].
            var skColor = new SKColor(ToByte(SRGBTransferFunction(SRGB[0]) * 255),
                                      ToByte(SRGBTransferFunction(SRGB[1]) * 255),
                                      ToByte(SRGBTransferFunction(SRGB[2]) * 255));

            if (alpha != null)
            {
                skColor = skColor.WithAlpha((byte)(alpha * 255));
            }
            return(skColor);
        }
Beispiel #7
0
        public override SKColor GetSKColor(float[] components, float?alpha = null)
        {
            var g       = (byte)Math.Round(components[0] * 255);
            var skColor = new SKColor(g, g, g);

            if (alpha != null)
            {
                skColor = skColor.WithAlpha((byte)(alpha.Value * 255));
            }
            return(skColor);
        }
Beispiel #8
0
        public override SKColor GetSKColor(Color color, float?alpha = null)
        {
            var spaceColor = (DeviceGrayColor)color;
            var g          = (byte)Math.Round(spaceColor.G * 255);
            var skColor    = new SKColor(g, g, g);

            if (alpha != null)
            {
                skColor = skColor.WithAlpha((byte)(alpha.Value * 255));
            }
            return(skColor);
        }
Beispiel #9
0
    private async Task GetColorAsync(SKColor color)
    {
        // Force alpha to 255.
        color = color.WithAlpha(0xFF);

        // Get raw uint32 value from color by extracting rgb values.
        uint raw = (uint)(color.Red << 16 | color.Green << 8 | color.Blue);

        // Get HSL and HSV values.
        var hsl = new Vector3();
        var hsv = new Vector3();

        color.ToHsl(out hsl.X, out hsl.Y, out hsl.Z);
        color.ToHsv(out hsv.X, out hsv.Y, out hsv.Z);

        // Draw color to image.
        var bitmap  = new SKBitmap(128, 128);
        var surface = SKSurface.Create(bitmap.Info);

        using (var canvas = surface.Canvas)
        {
            canvas.Clear(color);
            canvas.Flush();
        }

        // Encode image to stream for uploading.
        var stream = surface.Snapshot().Encode().AsStream();

        // Use hex code as filename but omit the pound sign.
        string fileName = $"{raw.ToString("X6")}.png";

        // Construct embed with color information and thumbnail.
        var embed = new EmbedBuilder()
                    .WithThumbnailUrl($"attachment://{fileName}")
                    .WithColor(raw)
                    .AddField(
            // Strip alpha from hex.
            "HEX",
            $"`#{raw.ToString("X6")}`")
                    .AddField(
            "RGB",
            $"`rgb({color.Red.ToString()}, {color.Green.ToString()}, {color.Blue.ToString()})`")
                    .AddField(
            "HSL",
            $"**H**: {hsl.X.ToString("F2")}, **S**: {hsl.Y.ToString("F2")}, **L**: {hsl.Z.ToString("F2")}")
                    .AddField(
            "HSV",
            $"**H**: {hsv.X.ToString("F2")}, **S**: {hsv.Y.ToString("F2")}, **V**: {hsv.Z.ToString("F2")}")
                    .Build();

        await Context.Interaction.RespondWithFileAsync(stream, fileName, embed : embed);
    }
Beispiel #10
0
        private SKShader CreateXGradient(SKPoint[] points, IEnumerable <ChartEntry> entries, SKColor?serieColor, byte alpha = 255)
        {
            var startX = points.First().X;
            var endX   = points.Last().X;
            var rangeX = endX - startX;

            return(SKShader.CreateLinearGradient(
                       new SKPoint(startX, 0),
                       new SKPoint(endX, 0),
                       entries.Select(x => serieColor?.WithAlpha(alpha) ?? x.Color.WithAlpha(alpha)).ToArray(),
                       null,
                       SKShaderTileMode.Clamp));
        }
Beispiel #11
0
        public override SKColor GetSKColor(Color color, float?alpha = null)
        {
            DeviceRGBColor spaceColor = (DeviceRGBColor)color;
            var            skColor    = new SKColor(
                (byte)Math.Round(spaceColor.R * 255),
                (byte)Math.Round(spaceColor.G * 255),
                (byte)Math.Round(spaceColor.B * 255));

            if (alpha != null)
            {
                skColor = skColor.WithAlpha((byte)(alpha.Value * 255));
            }
            return(skColor);
        }
        public override void CreateResources()
        {
            colorConstruction = new SKColor(0xF0, 0x52, 0x35); //SKColors.Red;
            colorConstruction = colorConstruction.WithAlpha(ConvertAlpha(0.4F));

            colorPerpConstruction = new SKColor(0xF0, 0x52, 0x35); //SKColors.Orange;
            colorPerpConstruction = colorPerpConstruction.WithAlpha(ConvertAlpha(0.4F));

            colorAttributes = new SKColor(0xF1, 0xf1, 0xd9); // SKColors.Yellow;
            colorAttributes = colorAttributes.WithAlpha(ConvertAlpha(0.4F));

            colorPathMain = new SKColor(0x85, 0xD4, 0xE3); //SKColors.White;
            colorPathMain = colorPathMain.WithAlpha(ConvertAlpha(1F));

            colorSA = new SKColor(0x85, 0xD4, 0xE3); //SKColors.DeepSkyBlue;
            colorSA = colorSA.WithAlpha(ConvertAlpha(1F));

            colorHA = new SKColor(0x85, 0xD4, 0xE3); //SKColors.DodgerBlue;
            colorHA = colorHA.WithAlpha(ConvertAlpha(1F));

            colorText = new SKColor(0x85, 0xD4, 0xE3); //SKColors.White;
            colorText = colorText.WithAlpha(ConvertAlpha(1F));

            colorFillMain = new SKColor(0x17, 0x1f, 0x21);// SKColors.Gray;
            colorFillMain = colorFillMain.WithAlpha(ConvertAlpha(0.8F));

            colorFill1 = new SKColor(0xF1, 0xf1, 0xd9);//SKColors.LightBlue;
            colorFill1 = colorFill1.WithAlpha(ConvertAlpha(0.5F));

            colorPath1 = new SKColor(0xF1, 0xf1, 0xd9); //SKColors.White;
            colorPath1 = colorPath1.WithAlpha(ConvertAlpha(1F));

            colorFill2 = new SKColor(0x17, 0x1f, 0x21);//SKColors.LightBlue;
            colorFill2 = colorFill2.WithAlpha(ConvertAlpha(0.8F));

            colorTransparent = SKColors.White;
            colorTransparent = colorTransparent.WithAlpha(ConvertAlpha(0F));

            colorPathPrint = SKColors.Black;
            colorPathPrint = colorPathPrint.WithAlpha(ConvertAlpha(1F));

            colorTextPrint = SKColors.Black;
            colorTextPrint = colorTextPrint.WithAlpha(ConvertAlpha(0.3F));

            colorFillPrint = SKColors.Gray;
            colorFillPrint = colorFillPrint.WithAlpha(ConvertAlpha(0.1F));
        }
Beispiel #13
0
 /// <inheritdoc />
 protected override void DrawBarArea(SKCanvas canvas, float headerHeight, SKSize itemSize, SKSize barSize, SKColor color, float origin, float value, float barX, float barY)
 {
     if (BarAreaAlpha > 0)
     {
         using (var paint = new SKPaint
         {
             Style = SKPaintStyle.Fill,
             Color = color.WithAlpha((byte)(this.BarAreaAlpha * this.AnimationProgress)),
         })
         {
             var max    = value > 0 ? headerHeight : headerHeight + itemSize.Height;
             var height = Math.Abs(max - barY);
             var y      = Math.Min(max, barY);
             canvas.DrawRect(SKRect.Create(barX - (itemSize.Width / 2), y, barSize.Width, height), paint);
         }
     }
 }
Beispiel #14
0
 /// <inheritdoc />
 protected override void DrawBarArea(SKCanvas canvas, float headerHeight, SKSize itemSize, SKSize barSize, SKColor color, float origin, float value, float barX, float barY)
 {
     if (PointAreaAlpha > 0)
     {
         var y = Math.Min(origin, barY);
         using (var shader = SKShader.CreateLinearGradient(new SKPoint(0, origin), new SKPoint(0, barY), new[] { color.WithAlpha(PointAreaAlpha), color.WithAlpha((byte)(PointAreaAlpha / 3)) }, null, SKShaderTileMode.Clamp))
             using (var paint = new SKPaint
             {
                 Style = SKPaintStyle.Fill,
                 Color = color.WithAlpha(PointAreaAlpha),
             })
             {
                 paint.Shader = shader;
                 var height = Math.Max(2, Math.Abs(origin - barY));
                 canvas.DrawRect(SKRect.Create(barX - (itemSize.Width / 2) + (barSize.Width / 2) - (PointSize / 2), y, PointSize, height), paint);
             }
     }
 }
Beispiel #15
0
        private static void DrawPolygon(SKCanvas canvas, SKColor color, TmxMap tmxMap, TmxObjectPolygon tmxPolygon)
        {
            using (SKPaint paint = new SKPaint())
                using (SKPath path = new SKPath())
                {
                    var points = TmxMath.GetPointsInMapSpace(tmxMap, tmxPolygon).ToSkPointArray();
                    path.AddPoly(points);

                    paint.Style       = SKPaintStyle.Fill;
                    paint.StrokeWidth = StrokeWidthThick;
                    paint.Color       = color.WithAlpha(128);
                    canvas.DrawPath(path, paint);

                    paint.Style       = SKPaintStyle.Stroke;
                    paint.StrokeWidth = StrokeWidthThick;
                    paint.Color       = color;
                    canvas.DrawPath(path, paint);
                }
        }
        private SKColor Calculate(double A, float?alpha = null)
        {
            // A represents a gray component of a calibrated gray space.
            // A <---> AG in the spec
            var AG = Math.Pow(A, G);
            // Computes L as per spec. ( = cs.YW * AG )
            // Except if other than default BlackPoint values are used.
            var L = YW * AG;
            // http://www.poynton.com/notes/colour_and_gamma/ColorFAQ.html, Ch 4.
            // Convert values to rgb range [0, 255].
            var val     = ToByte(Math.Max(295.8 * Math.Pow(L, 0.333333333333333333) - 40.8, 0));
            var skColor = new SKColor(val, val, val);

            if (alpha != null)
            {
                skColor = skColor.WithAlpha((byte)(alpha * 255));
            }
            return(skColor);
        }
Beispiel #17
0
        internal static void DrawBoundingBox(
            SKCanvas canvas,
            float width,
            float height,
            float xmin,
            float ymin,
            float xmax,
            float ymax,
            double ticks,
            bool applyAlpha = false)
        {
            if (applyAlpha && ticks < 0.1d)
            {
                canvas.Clear();
                return;
            }

            var top    = xmin * height;
            var left   = ymin * width;
            var bottom = xmax * height;
            var right  = ymax * width;

            if (applyAlpha)
            {
                var alpha = (byte)(ticks * byte.MaxValue);
                boundingBoxPaint.Color = boundingBoxColor.WithAlpha(alpha);
            }
            else
            {
                boundingBoxPaint.Color = boundingBoxColor;
            }

            boundingBoxShadowPaint.Color = boundingBoxPaint.Color;

            var rect = new SKRect(left, top, right, bottom);

            canvas.DrawRoundRect(rect, boundingBoxCornerRadius, boundingBoxShadowPaint);
            canvas.DrawRoundRect(rect, boundingBoxCornerRadius, boundingBoxPaint);
        }
Beispiel #18
0
    private void DrawInnerGradient(SKCanvas canvas)
    {
        // gamma correction
        var colors = Enumerable
                     .Range(0, InnerGradientSize)
                     .Select(x => 1f - x / (float)InnerGradientSize)
                     .Select(x => Math.Pow(x, 2f))
                     .Select(x => (byte)(x * 255))
                     .Select(x => InnerGradientColor.WithAlpha(x))
                     .ToArray();

        using var fogPaint = new SKPaint
              {
                  Shader = SKShader.CreateLinearGradient(
                      new SKPoint(0, 0),
                      new SKPoint(0, InnerGradientSize),
                      colors,
                      SKShaderTileMode.Clamp)
              };

        canvas.DrawRect(0, 0, Width, InnerGradientSize, fogPaint);
    }
Beispiel #19
0
        public override SKColor GetColor(Color color, double?alpha = null)
        {
            DeviceCMYKColor spaceColor = (DeviceCMYKColor)color;

            /*
             * NOTE: This convertion algorithm was from Apache FOP.
             */
            //FIXME: verify whether this algorithm is effective (limit checking seems quite ugly to me!).
            //float keyCorrection = (float)spaceColor.K;// / 2.5f;
            //int r = (int)((1 - Math.Min(1, spaceColor.C + keyCorrection)) * 255); if (r < 0) { r = 0; }
            //int g = (int)((1 - Math.Min(1, spaceColor.M + keyCorrection)) * 255); if (g < 0) { g = 0; }
            //int b = (int)((1 - Math.Min(1, spaceColor.Y + keyCorrection)) * 255); if (b < 0) { b = 0; }
            var r       = (int)(255 * (1 - spaceColor.C) * (1 - spaceColor.K));
            var g       = (int)(255 * (1 - spaceColor.M) * (1 - spaceColor.K));
            var b       = (int)(255 * (1 - spaceColor.Y) * (1 - spaceColor.K));
            var skColor = new SKColor((byte)r, (byte)g, (byte)b);

            if (alpha != null)
            {
                skColor = skColor.WithAlpha((byte)(alpha.Value * 255));
            }
            return(skColor);
        }
Beispiel #20
0
        public void ColorWithComponent()
        {
            var color = new SKColor();

            Assert.AreEqual(0, color.Red);
            Assert.AreEqual(0, color.Green);
            Assert.AreEqual(0, color.Blue);
            Assert.AreEqual(0, color.Alpha);

            var red = color.WithRed(255);

            Assert.AreEqual(255, red.Red);
            Assert.AreEqual(0, red.Green);
            Assert.AreEqual(0, red.Blue);
            Assert.AreEqual(0, red.Alpha);

            var green = color.WithGreen(255);

            Assert.AreEqual(0, green.Red);
            Assert.AreEqual(255, green.Green);
            Assert.AreEqual(0, green.Blue);
            Assert.AreEqual(0, green.Alpha);

            var blue = color.WithBlue(255);

            Assert.AreEqual(0, blue.Red);
            Assert.AreEqual(0, blue.Green);
            Assert.AreEqual(255, blue.Blue);
            Assert.AreEqual(0, blue.Alpha);

            var alpha = color.WithAlpha(255);

            Assert.AreEqual(0, alpha.Red);
            Assert.AreEqual(0, alpha.Green);
            Assert.AreEqual(0, alpha.Blue);
            Assert.AreEqual(255, alpha.Alpha);
        }
        private void DrawGraph(List <JArray> dataArray, SKCanvas canvas, int width, int height)
        {
            dataArray = GetLimits(dataArray);

            CanvasWidth  = width - (int)(CANVAS_WIDTH * width);
            CanvasHeight = height - (int)(CANVAS_HEIGHT * height);

            // label for Axises
            SKPaint labelPaint = new SKPaint
            {
                Color       = SKColors.Black,
                TextAlign   = SKTextAlign.Center,
                IsAntialias = true
            };

            // different text sizes depending on platforms
            if (Device.RuntimePlatform == Device.Android)
            {
                labelPaint.TextSize = 25;
            }
            else if (Device.RuntimePlatform == Device.UWP)
            {
                labelPaint.TextSize = 13;
            }

            bool first = true;

            foreach (JArray data in dataArray)
            {
                // quantity to add each iteration
                float xdelta = (float)CanvasWidth / (data.Count - 1);

                // starting point
                float x = HORIZONTAL_PADDING * width;

                // starting point
                float initial_y = CanvasHeight + VERTICAL_PADDING * height;

                // create the graph's path
                SKPath path = new SKPath();

                // create graph outline
                SKPath outline = new SKPath();

                // create contour for graph
                path.MoveTo(x, initial_y);

                for (int i = 0; i < data.Count; i++)
                {
                    // quote information
                    JObject session = (JObject)data[i];

                    // normalize
                    float y = 1 - ((float)session["close"] - MinValueY) / RangeLimits;

                    // actual pixel value
                    y = CanvasHeight * y + VERTICAL_PADDING * height;

                    // if first iteration, create countour, otherwise create outlining line
                    if (i == 0)
                    {
                        outline.MoveTo(x, y);
                    }
                    else
                    {
                        outline.LineTo(x, y);
                    }

                    path.LineTo(x, y);

                    // draw label for X axis
                    DrawLabelXAxis(i, canvas, labelPaint, session, x, width, height);

                    x += xdelta;
                }
                float final_x = width - ((float)CANVAS_WIDTH - HORIZONTAL_PADDING) * width;
                path.LineTo(final_x, CanvasHeight + VERTICAL_PADDING * height);
                path.Close();

                SKPaint axisPaint = new SKPaint
                {
                    Style       = SKPaintStyle.Stroke,
                    Color       = SKColors.Black,
                    StrokeWidth = 1
                };

                // reddish color
                Color firstColor = Color.FromRgb(225, 107, 90);

                // blueish color
                Color secondColor = Color.FromRgb(74, 184, 161);

                SKColor redColor  = firstColor.ToSKColor();
                SKColor blueColor = secondColor.ToSKColor();

                // create the stroke paint
                SKPaint strokePaint = new SKPaint
                {
                    Style       = SKPaintStyle.Stroke,
                    Color       = first ? blueColor : redColor,
                    IsAntialias = true,
                    StrokeWidth = 4
                };

                // create the fill paint
                SKPaint fillPaint = new SKPaint
                {
                    Style = SKPaintStyle.Fill,
                    Color = first ? blueColor.WithAlpha(150) : redColor.WithAlpha(150)
                };

                DrawLabels(canvas, data, redColor, blueColor, first, width, height);
                first = false;

                // draw X Axis
                DrawXAxis(canvas, axisPaint, width, height);

                // draw Y Axis
                DrawYAxis(canvas, axisPaint, labelPaint, width, height);

                // draw the graph paths
                canvas.DrawPath(outline, strokePaint);
                canvas.DrawPath(path, fillPaint);
            }
        }
Beispiel #22
0
 public void SetFixOpacity(float o)
 {
     variableOpacity = false;
     opacity         = o;
     paint.Color     = color.WithAlpha((byte)(color.Alpha * opacity));
 }
Beispiel #23
0
 public void SetFixColor(SKColor c)
 {
     variableColor = false;
     color         = c;
     paint.Color   = color.WithAlpha((byte)(color.Alpha * opacity));
 }
Beispiel #24
0
        public void ColorWithComponent()
        {
            var color = new SKColor();
            Assert.AreEqual(0, color.Red);
            Assert.AreEqual(0, color.Green);
            Assert.AreEqual(0, color.Blue);
            Assert.AreEqual(0, color.Alpha);

            var red = color.WithRed(255);
            Assert.AreEqual(255, red.Red);
            Assert.AreEqual(0, red.Green);
            Assert.AreEqual(0, red.Blue);
            Assert.AreEqual(0, red.Alpha);

            var green = color.WithGreen(255);
            Assert.AreEqual(0, green.Red);
            Assert.AreEqual(255, green.Green);
            Assert.AreEqual(0, green.Blue);
            Assert.AreEqual(0, green.Alpha);

            var blue = color.WithBlue(255);
            Assert.AreEqual(0, blue.Red);
            Assert.AreEqual(0, blue.Green);
            Assert.AreEqual(255, blue.Blue);
            Assert.AreEqual(0, blue.Alpha);

            var alpha = color.WithAlpha(255);
            Assert.AreEqual(0, alpha.Red);
            Assert.AreEqual(0, alpha.Green);
            Assert.AreEqual(0, alpha.Blue);
            Assert.AreEqual(255, alpha.Alpha);
        }
Beispiel #25
0
        //percentage is between 0.0 and 1.0
        public static SKColor WithAlpha(this SKColor colour, float percentage)
        {
            byte alphaByte = (byte)(255 * percentage);

            return(colour.WithAlpha(alphaByte));
        }
        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;
        }
        // Mozilla Pdf.js
        // The coefficients below was found using numerical analysis: the method of
        // steepest descent for the sum((f_i - color_value_i)^2) for r/g/b colors,
        // where color_value is the tabular value from the table of sampled RGB colors
        // from CMYK US Web Coated (SWOP) colorspace, and f_i is the corresponding
        // CMYK color conversion using the estimation below:
        //   f(A, B,.. N) = Acc+Bcm+Ccy+Dck+c+Fmm+Gmy+Hmk+Im+Jyy+Kyk+Ly+Mkk+Nk+255
        SKColor Calculate(double c, double m, double y, double k, float?alpha = null)
        {
            var r =
                255 +
                c *
                (-4.387332384609988 * c +
                 54.48615194189176 * m +
                 18.82290502165302 * y +
                 212.25662451639585 * k +
                 -285.2331026137004) +
                m *
                (1.7149763477362134 * m -
                 5.6096736904047315 * y +
                 -17.873870861415444 * k -
                 5.497006427196366) +
                y *
                (-2.5217340131683033 * y - 21.248923337353073 * k + 17.5119270841813) +
                k * (-21.86122147463605 * k - 189.48180835922747);

            var g =
                255 +
                c *
                (8.841041422036149 * c +
                 60.118027045597366 * m +
                 6.871425592049007 * y +
                 31.159100130055922 * k +
                 -79.2970844816548) +
                m *
                (-15.310361306967817 * m +
                 17.575251261109482 * y +
                 131.35250912493976 * k -
                 190.9453302588951) +
                y * (4.444339102852739 * y + 9.8632861493405 * k - 24.86741582555878) +
                k * (-20.737325471181034 * k - 187.80453709719578);

            var b =
                255 +
                c *
                (0.8842522430003296 * c +
                 8.078677503112928 * m +
                 30.89978309703729 * y -
                 0.23883238689178934 * k +
                 -14.183576799673286) +
                m *
                (10.49593273432072 * m +
                 63.02378494754052 * y +
                 50.606957656360734 * k -
                 112.23884253719248) +
                y *
                (0.03296041114873217 * y +
                 115.60384449646641 * k +
                 -193.58209356861505) +
                k * (-22.33816807309886 * k - 180.12613974708367);

            var skColor = new SKColor(ToByte(r), ToByte(g), ToByte(b));

            if (alpha != null)
            {
                skColor = skColor.WithAlpha((byte)(alpha.Value * 255));
            }
            return(skColor);
        }
Beispiel #28
0
 public static SKColor Transparency(this SKColor color, double amount)
 {
     return(color.WithAlpha((byte)(color.Alpha * amount)));
 }
Beispiel #29
0
        private protected override void UpdatePaintCore(SKPaint paint, SKRect bounds)
        {
            var center         = EllipseCenter.ToSKPoint();
            var gradientOrigin = EllipseCenter.ToSKPoint() + GradientOriginOffset.ToSKPoint();
            var radius         = EllipseRadius.ToSKPoint();
            var transform      = CreateTransformMatrix(bounds);

            // Transform the points into absolute coordinates.
            if (MappingMode == CompositionMappingMode.Relative)
            {
                // If the point are provided relative they must be multiplied by bounds.
                center.X *= bounds.Width;
                center.Y *= bounds.Height;

                gradientOrigin.X *= bounds.Width;
                gradientOrigin.Y *= bounds.Height;

                radius.X *= bounds.Width;
                radius.Y *= bounds.Height;
            }

            // Translate gradient points by bounds offset.
            center.X += bounds.Left;
            center.Y += bounds.Top;

            gradientOrigin.X += bounds.Left;
            gradientOrigin.Y += bounds.Top;
            //

            // SkiaSharp does not allow explicit definition of RadiusX and RadiusY.
            // Compute transformation matrix to compensate.
            ComputeRadiusAndScale(center, radius.X, radius.Y, out float gradientRadius, out SKMatrix matrix);

            // Clean up old shader
            if (paint.Shader != null)
            {
                paint.Shader.Dispose();
                paint.Shader = null;
            }

            if (gradientRadius > 0)
            {
                // Create radial gradient shader.
                SKShader shader =
                    SKShader.CreateTwoPointConicalGradient(
                        /* start */ gradientOrigin, /* start radius */ 0,
                        /* end */ center, /* gradient radius */ gradientRadius,
                        Colors, ColorPositions,
                        TileMode, transform.PreConcat(matrix));

                paint.Shader = shader;
                paint.Color  = SKColors.Black.WithAlpha((byte)(Compositor.CurrentOpacity * 255));
            }
            else
            {
                // With radius equal to 0, SkiaSharp does not draw anything.
                // But we expect last gradient color.

                // If there are no gradient stops available, use transparent.
                SKColor color = SKColors.Transparent;
                if (Colors !.Length > 0)
                {
                    color = Colors[Colors.Length - 1];
                }

                double alpha = (color.Alpha / 255.0) * Compositor.CurrentOpacity;
                paint.Color = color.WithAlpha((byte)(alpha * 255));
            }
        }
Beispiel #30
0
        public static SKColor AsTransparency(this SKColor color)
        {
            var transparency = 0.5 * (1 + Math.Sin(1 * 2 * Math.PI));

            return(color.WithAlpha((byte)(0xFF * (1 - transparency))));
        }
Beispiel #31
0
        // If decoding is needed maxVal should be 2^bits per component - 1.
        public SKColor Calculate(float Ls, float As, float Bs, float?maxVal, float?alpha = null)
        {
            // XXX: Lab input is in the range of [0, 100], [amin, amax], [bmin, bmax]
            // not the usual [0, 1]. If a command like setFillColor is used the src
            // values will already be within the correct range. However, if we are
            // converting an image we have to map the values to the correct range given
            // above.
            // Ls,as,bs <---> L*,a*,b* in the spec
            if (maxVal != null)
            {
                Ls = Decode(Ls, (float)maxVal, 0, 100);
                As = Decode(As, (float)maxVal, amin, amax);
                Bs = Decode(Bs, (float)maxVal, bmin, bmax);
            }

            // Adjust limits of 'as' and 'bs'
            if (As > amax)
            {
                As = amax;
            }
            else if (As < amin)
            {
                As = amin;
            }
            if (Bs > bmax)
            {
                Bs = bmax;
            }
            else if (Bs < bmin)
            {
                Bs = bmin;
            }

            // Computes intermediate variables X,Y,Z as per spec
            var M = (Ls + 16) / 116;
            var L = M + As / 500;
            var N = M - Bs / 200;

            var X = XW * FnG(L);
            var Y = YW * FnG(M);
            var Z = ZW * FnG(N);

            float r, g, b;

            // Using different conversions for D50 and D65 white points,
            // per http://www.color.org/srgb.pdf
            if (ZW < 1)
            {
                // Assuming D50 (X=0.9642, Y=1.00, Z=0.8249)
                r = X * 3.1339F + Y * -1.617F + Z * -0.4906F;
                g = X * -0.9785F + Y * 1.916F + Z * 0.0333F;
                b = X * 0.072F + Y * -0.229F + Z * 1.4057F;
            }
            else
            {
                // Assuming D65 (X=0.9505, Y=1.00, Z=1.0888)
                r = X * 3.2406F + Y * -1.5372F + Z * -0.4986F;
                g = X * -0.9689F + Y * 1.8758F + Z * 0.0415F;
                b = X * 0.0557F + Y * -0.204F + Z * 1.057F;
            }
            // Convert the color values to the [0,255] range (clamping is automatic).
            var skColor = new SKColor(
                ToByte(Math.Sqrt(r) * 255),
                ToByte(Math.Sqrt(g) * 255),
                ToByte(Math.Sqrt(b) * 255));

            if (alpha != null)
            {
                skColor = skColor.WithAlpha((byte)(alpha * 255));
            }
            return(skColor);
        }