Beispiel #1
0
        public ImageSprite(Texture2D texture, ImageSourceId sourceId)
        {
            image = new Image();
            var source = texture.GetSpecialSource(sourceId.ForTextureLookup);

            image.Source = source;
            image.Width  = source.PixelWidth;
            image.Height = source.PixelHeight;

            base.Create(image, sourceId.Cache, true);

            if (sourceId.DynamicColor)
            {
                // Note: This tint effect does not apply additive blending
                //       (because theoretically the non-additive version should be faster).
                //       Additive-ness is already applied at the image source.
                //       (Ditto for Opaque blending)
                canvas.Effect = tintEffect = TintEffect.Create(TintEffectMode.Normal);
            }

            if (sourceId.DynamicRectangle)
            {
                image.Clip = clipGeometry = new SWM.RectangleGeometry();
            }
        }
        public Image Create(Image img)
        {
            var    effect = new TintEffect(90, 30);
            Bitmap newImg = new Bitmap(img);

            newImg.ApplyEffect(effect, Rectangle.Empty);
            return(newImg);
        }
Beispiel #3
0
        WriteableBitmap CreateSourceFor(ImageSourceId id)
        {
            BitmapSource original = ImageSource;

            // Note: need to recreate temporaryImage each time, because Silverlight
            //       has some very strange ideas about when to update the image dimensions
            Image temporaryImage = new Image();

            TintEffect temporaryTintEffect = null;

            if (id.WantsPreTint)
            {
                temporaryTintEffect       = TintEffect.Create(id.TintEffectMode);
                temporaryImage.Effect     = temporaryTintEffect;
                temporaryTintEffect.Color = id.ColorForPreTint;
            }

            temporaryImage.Width  = original.PixelWidth;
            temporaryImage.Height = original.PixelHeight;
            temporaryImage.Source = original;


            int width, height;

            SWM.TranslateTransform transform;

            if (id.UseOriginalDimentions)
            {
                width     = original.PixelWidth;
                height    = original.PixelHeight;
                transform = null;
            }
            else
            {
                width  = id.SourceWidth;
                height = id.SourceHeight;

                transform   = new SWM.TranslateTransform();
                transform.X = -id.SourceX;
                transform.Y = -id.SourceY;
            }

            WriteableBitmap output = new WriteableBitmap(width, height);

            output.Render(temporaryImage, transform);
            output.Invalidate();

            if (temporaryTintEffect != null)
            {
                temporaryImage.Effect = null;
                temporaryTintEffect.Release();
            }

            return(output);
        }
Beispiel #4
0
        private Xamarin.Forms.Color GetTintColor()
        {
            var tintColor = TintEffect.GetTintColor(Element);

            if (tintColor == Xamarin.Forms.Color.Default)
            {
                return((Xamarin.Forms.Color)Xamarin.Forms.Application.Current.Resources["TintColor"]);
            }
            else
            {
                return(tintColor);
            }
        }
Beispiel #5
0
        public void Ctor_Reader()
        {
            var reader = new MetafileReader(new byte[]
            {
                /* Hue */ 0x01, 0x00, 0x00, 0x00,
                /* Amount */ 0x02, 0x00, 0x00, 0x00
            }, 0);

            var effect = new TintEffect(reader);

            Assert.Equal(1, effect.Hue);
            Assert.Equal(2, effect.Amount);
            Assert.Equal(8u, effect.Size);
            Assert.Equal(new Guid("{1077AF00-2848-4441-9489-44AD4C2D7A2C}"), effect.Identifier);
        }
        private ICanvasImage CreateTint()
        {
            if (!TintEffect.IsSupported)
            {
                return CreateNotSupportedMessage(requiresWin10_14393);
            }

            textLabel = requiresWin10_14393;

            var tintEffect = new TintEffect
            {
                Source = bitmapTiger
            };

            // Animation changes the tint color.
            animationFunction = elapsedTime =>
            {
                var r = (byte)(128 + Math.Sin(elapsedTime * 3) * 127);
                var g = (byte)(128 + Math.Sin(elapsedTime * 4) * 127);
                var b = (byte)(128 + Math.Sin(elapsedTime * 5) * 127);

                tintEffect.Color = Color.FromArgb(255, r, g, b);
            };

            return tintEffect;
        }
Beispiel #7
0
        private void Canvas_Draw(ICanvasAnimatedControl sender, CanvasAnimatedDrawEventArgs args)
        {
            if (Globals.DrawReady)
            {
                for (int i = 0; i < shipImages.Length; i++)
                {
                    lock (clickedLock)
                    {
                        if (Globals.player.fleet[i] != null)
                        {
                            double x    = Globals.player.fleet[i].mainPoint.X;
                            double y    = Globals.player.fleet[i].mainPoint.Y;
                            float  xPos = (float)Globals.player.homeGrid[(int)x][(int)y].ScreenPoint.X;
                            float  yPos = (float)Globals.player.homeGrid[(int)x][(int)y].ScreenPoint.Y;

                            args.DrawingSession.DrawImage(shipShadows[i], xPos, yPos);
                            args.DrawingSession.DrawImage(shipImages[i], xPos, yPos);
                        }
                    }
                }
                lock (hoverLock)
                {
                    if (hoveredShip != null)
                    {
                        float drawX       = (float)Globals.player.homeGrid[(int)(hoveredShip.mainPoint.X)][(int)(hoveredShip.mainPoint.Y)].ScreenPoint.X;
                        float drawY       = (float)Globals.player.homeGrid[(int)(hoveredShip.mainPoint.X)][(int)(hoveredShip.mainPoint.Y)].ScreenPoint.Y;
                        float imageWidth  = (float)shipImages[hoveredShip.Length - 2].GetBounds(screenCanvas).Width;
                        float imageHeight = (float)shipImages[hoveredShip.Length - 2].GetBounds(screenCanvas).Height;
                        args.DrawingSession.DrawRectangle(drawX, drawY, imageWidth, imageHeight, Windows.UI.Colors.Red, 3);
                        var rotateResult    = hoveredShip.GetRotationPosition();
                        int imageIndex      = Array.IndexOf(shipNames, hoveredShip.ShipName);
                        var transparentShip = new OpacityEffect();
                        if (hoveredShip.Vertical)
                        {
                            transparentShip.Source = horizontalShips[imageIndex];
                        }
                        else
                        {
                            transparentShip.Source = verticalShips[imageIndex];
                        }
                        transparentShip.Opacity = (float)0.6;
                        if (rotateResult.Item1.Length > 0 && rotateResult.Item2)
                        {
                            args.DrawingSession.DrawImage(transparentShip, drawX, drawY);
                        }
                        else if (rotateResult.Item1.Length > 0)
                        {
                            var tintedShip = new TintEffect()
                            {
                                Source = transparentShip,
                                Color  = Windows.UI.Colors.Red
                            };
                            args.DrawingSession.DrawImage(tintedShip, drawX, drawY);
                        }
                    }
                }
                lock (clickedLock)
                {
                    if (moveError != null)
                    {
                        var tintedShip = new TintEffect
                        {
                            Source = shipImages[clickedShip.Length - 2],
                            Color  = Windows.UI.Colors.Red
                        };
                        var transparentShip = new OpacityEffect
                        {
                            Source  = tintedShip,
                            Opacity = (float)0.75
                        };
                        float xPos = (float)Globals.player.homeGrid[(int)moveError.Item1.X][(int)moveError.Item1.Y].ScreenPoint.X;
                        float yPos = (float)Globals.player.homeGrid[(int)moveError.Item1.X][(int)moveError.Item1.Y].ScreenPoint.Y;
                        args.DrawingSession.DrawImage(transparentShip, xPos, yPos);
                    }
                }
            }
        }
        private async Task ChatPhotoAsync(UpdateFileGenerationStart update, string[] args)
        {
            try
            {
                var conversion = JsonConvert.DeserializeObject <ChatPhotoConversion>(args[2]);

                var sticker = await _protoService.SendAsync(new GetFile(conversion.StickerFileId)) as Telegram.Td.Api.File;

                if (sticker == null || !sticker.Local.IsFileExisting())
                {
                    _protoService.Send(new FinishFileGeneration(update.GenerationId, new Error(500, "FILE_GENERATE_LOCATION_INVALID No sticker found")));
                    return;
                }

                Background background = null;

                var backgroundLink = await _protoService.SendAsync(new GetInternalLinkType(conversion.BackgroundUrl ?? string.Empty)) as InternalLinkTypeBackground;

                if (backgroundLink != null)
                {
                    background = await _protoService.SendAsync(new SearchBackground(backgroundLink.BackgroundName)) as Background;
                }
                else
                {
                    var freeform = new[] { 0xDBDDBB, 0x6BA587, 0xD5D88D, 0x88B884 };
                    background = new Background(0, true, false, string.Empty,
                                                new Document(string.Empty, "application/x-tgwallpattern", null, null, TdExtensions.GetLocalFile("Assets\\Background.tgv", "Background")),
                                                new BackgroundTypePattern(new BackgroundFillFreeformGradient(freeform), 50, false, false));
                }

                if (background == null || (background.Document != null && !background.Document.DocumentValue.Local.IsFileExisting()))
                {
                    _protoService.Send(new FinishFileGeneration(update.GenerationId, new Error(500, "FILE_GENERATE_LOCATION_INVALID No background found")));
                    return;
                }

                var device  = CanvasDevice.GetSharedDevice();
                var bitmaps = new List <CanvasBitmap>();

                var sfondo = new CanvasRenderTarget(device, 640, 640, 96, DirectXPixelFormat.B8G8R8A8UIntNormalized, CanvasAlphaMode.Premultiplied);

                using (var session = sfondo.CreateDrawingSession())
                {
                    if (background.Type is BackgroundTypePattern pattern)
                    {
                        if (pattern.Fill is BackgroundFillFreeformGradient freeform)
                        {
                            var colors    = freeform.GetColors();
                            var positions = new Vector2[]
                            {
                                new Vector2(0.80f, 0.10f),
                                new Vector2(0.35f, 0.25f),
                                new Vector2(0.20f, 0.90f),
                                new Vector2(0.65f, 0.75f),
                            };

                            using (var gradient = CanvasBitmap.CreateFromBytes(device, ChatBackgroundFreeform.GenerateGradientData(50, 50, colors, positions), 50, 50, DirectXPixelFormat.B8G8R8A8UIntNormalized))
                                using (var cache = await PlaceholderHelper.GetPatternBitmapAsync(device, null, background.Document.DocumentValue))
                                {
                                    using (var scale = new ScaleEffect {
                                        Source = gradient, BorderMode = EffectBorderMode.Hard, Scale = new Vector2(640f / 50f, 640f / 50f)
                                    })
                                        using (var colorize = new TintEffect {
                                            Source = cache, Color = Color.FromArgb(0x76, 00, 00, 00)
                                        })
                                            using (var tile = new BorderEffect {
                                                Source = colorize, ExtendX = CanvasEdgeBehavior.Wrap, ExtendY = CanvasEdgeBehavior.Wrap
                                            })
                                                using (var effect = new BlendEffect {
                                                    Foreground = tile, Background = scale, Mode = BlendEffectMode.Overlay
                                                })
                                                {
                                                    session.DrawImage(effect, new Rect(0, 0, 640, 640), new Rect(0, 0, 640, 640));
                                                }
                                }
                        }
                    }
                }

                bitmaps.Add(sfondo);

                var width  = (int)(512d * conversion.Scale);
                var height = (int)(512d * conversion.Scale);

                var animation = await Task.Run(() => LottieAnimation.LoadFromFile(sticker.Local.Path, new Windows.Graphics.SizeInt32 {
                    Width = width, Height = height
                }, false, null));

                if (animation == null)
                {
                    _protoService.Send(new FinishFileGeneration(update.GenerationId, new Error(500, "FILE_GENERATE_LOCATION_INVALID Can't load Lottie animation")));
                    return;
                }

                var composition = new MediaComposition();
                var layer       = new MediaOverlayLayer();

                var buffer = ArrayPool <byte> .Shared.Rent(width *height * 4);

                var framesPerUpdate = animation.FrameRate < 60 ? 1 : 2;
                var duration        = TimeSpan.Zero;

                for (int i = 0; i < animation.TotalFrame; i += framesPerUpdate)
                {
                    var bitmap = CanvasBitmap.CreateFromBytes(device, buffer, width, height, DirectXPixelFormat.B8G8R8A8UIntNormalized);
                    animation.RenderSync(bitmap, i);

                    var clip    = MediaClip.CreateFromSurface(bitmap, TimeSpan.FromMilliseconds(1000d / 30d));
                    var overlay = new MediaOverlay(clip, new Rect(320 - (width / 2d), 320 - (height / 2d), width, height), 1);

                    overlay.Delay = duration;

                    layer.Overlays.Add(overlay);
                    duration += clip.OriginalDuration;

                    bitmaps.Add(bitmap);
                }

                composition.OverlayLayers.Add(layer);
                composition.Clips.Add(MediaClip.CreateFromSurface(sfondo, duration));

                var temp = await _protoService.GetFileAsync(update.DestinationPath);

                var profile = MediaEncodingProfile.CreateMp4(VideoEncodingQuality.Auto);
                profile.Audio                       = null;
                profile.Video.Bitrate               = 1800000;
                profile.Video.Width                 = 640;
                profile.Video.Height                = 640;
                profile.Video.FrameRate.Numerator   = 30;
                profile.Video.FrameRate.Denominator = 1;

                var progress = composition.RenderToFileAsync(temp, MediaTrimmingPreference.Precise, profile);
                progress.Progress = (result, delta) =>
                {
                    _protoService.Send(new SetFileGenerationProgress(update.GenerationId, 100, (int)delta));
                };

                var result = await progress;
                if (result == TranscodeFailureReason.None)
                {
                    _protoService.Send(new FinishFileGeneration(update.GenerationId, null));
                }
                else
                {
                    _protoService.Send(new FinishFileGeneration(update.GenerationId, new Error(500, result.ToString())));
                }

                ArrayPool <byte> .Shared.Return(buffer);

                foreach (var bitmap in bitmaps)
                {
                    bitmap.Dispose();
                }
            }
            catch (Exception ex)
            {
                _protoService.Send(new FinishFileGeneration(update.GenerationId, new Error(500, "FILE_GENERATE_LOCATION_INVALID " + ex.ToString())));
            }
        }
Beispiel #9
0
        protected override void OnConnected()
        {
            _connected = true;
            _negative  = IsInverted;

            if (_recreate || (CompositionBrush == null && Surface != null))
            {
                _recreate = false;

                var surface      = Surface;
                var surfaceBrush = Window.Current.Compositor.CreateSurfaceBrush(surface);
                surfaceBrush.Stretch = CompositionStretch.None;

                var borderEffect = new BorderEffect()
                {
                    Source  = new CompositionEffectSourceParameter("Source"),
                    ExtendX = Microsoft.Graphics.Canvas.CanvasEdgeBehavior.Wrap,
                    ExtendY = Microsoft.Graphics.Canvas.CanvasEdgeBehavior.Wrap
                };

                IGraphicsEffect      effect;
                IEnumerable <string> animatableProperties;
                if (IsInverted)
                {
                    //var matrix = new ColorMatrixEffect
                    //{
                    //    ColorMatrix = new Matrix5x4
                    //    {
                    //        M11 = 1, M12 = 0, M13 = 0, M14 = 0,
                    //        M21 = 0, M22 = 1, M23 = 0, M24 = 0,
                    //        M31 = 0, M32 = 0, M33 = 1, M34 = 0,
                    //        M41 = 0, M42 = 0, M43 = 0, M44 =-1,
                    //        M51 = 0, M52 = 0, M53 = 0, M54 = 1
                    //    },
                    //    Source = borderEffect
                    //};
                    _tintEffect = null;

                    animatableProperties = new string[0];
                    effect = new GammaTransferEffect()
                    {
                        AlphaAmplitude = -1,
                        AlphaOffset    = 1,
                        RedDisable     = true,
                        GreenDisable   = true,
                        BlueDisable    = true,
                        Source         = new InvertEffect {
                            Source = borderEffect
                        }
                    };
                }
                else
                {
                    var tintEffect = _tintEffect = new TintEffect
                    {
                        Name   = "Tint",
                        Source = borderEffect,
                        Color  = Color.FromArgb((byte)(Intensity * 255), 0, 0, 0)
                    };

                    animatableProperties = new[] { "Tint.Color" };
                    effect = new BlendEffect
                    {
                        Background = tintEffect,
                        Foreground = new CompositionEffectSourceParameter("Backdrop"),
                        Mode       = BlendEffectMode.Overlay
                    };
                }

                var backdrop = Window.Current.Compositor.CreateBackdropBrush();

                var borderEffectFactory = Window.Current.Compositor.CreateEffectFactory(effect, animatableProperties);
                var borderEffectBrush   = borderEffectFactory.CreateBrush();
                borderEffectBrush.SetSourceParameter("Source", surfaceBrush);

                if (_tintEffect != null)
                {
                    borderEffectBrush.SetSourceParameter("Backdrop", backdrop);
                }

                CompositionBrush = borderEffectBrush;
            }
        }