示例#1
0
        private void ShowCanvas_Draw(CanvasControl sender, CanvasDrawEventArgs args)
        {
            if (isRender == false)
            {
                isRender = true;

                if (App.Setting.Paint != null)
                {
                    var space = App.Setting.PaintSpace * (float)Math.Sqrt(App.Setting.PaintWidth);
                    for (float x = 10; x < CanvasSize.Width - 10; x += space)
                    {
                        //根据画布的X位置,求Sin高度角度(一条上下弧线)
                        var   sinh = x / CanvasSize.Width * Math.PI * 2;
                        float h    = 20 * (float)Math.Sin(sinh);//上下浮动

                        //根据画布的X位置,求Sin大小角度(一个上凸曲线)
                        var         sins = x / CanvasSize.Width * Math.PI;
                        Vector2     s    = new Vector2((float)Math.Sin(sins));//大小浮动
                        ScaleEffect se   = new ScaleEffect {
                            Source = App.Setting.PaintShow, Scale = s
                        };

                        args.DrawingSession.DrawImage(se, x, (float)CanvasSize.Height / 2 + h);
                    }
                }
                isRender = false;
            }
        }
示例#2
0
        public void PaintSet(ICanvasResourceCreator rc, CanvasBitmap cb, float R, Color co)
        {
            //Paint:绘画
            Paint = new CanvasCommandList(rc);

            using (CanvasDrawingSession ds = Paint.CreateDrawingSession())
            {
                ds.FillEllipse(0, 0, R, R, PaintBrush(rc, R, PaintHard, PaintOpacity, co));

                ICanvasImage ci = new ScaleEffect
                {
                    Source = cb,
                    Scale  = new Vector2(2 * R / cb.SizeInPixels.Width)
                };
                ds.DrawImage(ci, -R, -R, ci.GetBounds(rc), 1, CanvasImageInterpolation.HighQualityCubic, CanvasComposite.DestinationIn);
            }



            //Show:展示
            var radius = (float)Math.Sqrt(R);

            PaintShow = new CanvasCommandList(rc);

            using (CanvasDrawingSession ds = PaintShow.CreateDrawingSession())
            {
                ds.FillEllipse(0, 0, radius, radius, PaintBrush(rc, radius, PaintHard, PaintOpacity, Colors.White));
                ICanvasImage ci = new ScaleEffect
                {
                    Source = cb,
                    Scale  = new Vector2(2 * radius / cb.SizeInPixels.Width)
                };
                ds.DrawImage(ci, -radius, -radius, ci.GetBounds(rc), 1, CanvasImageInterpolation.HighQualityCubic, CanvasComposite.DestinationIn);
            }
        }
示例#3
0
        //Render:When your image has changed, call it
        public void Render(ICanvasResourceCreator creator, float scaleX, float scaleY, ICanvasImage image)
        {
            //Scale :zoom up
            ScaleEffect effect = new ScaleEffect
            {
                Source            = image,
                Scale             = new Vector2(1 / scaleX, 1 / scaleY),
                InterpolationMode = CanvasImageInterpolation.NearestNeighbor,
            };
            //Crop:So that it does not exceed the canvas boundary
            Rect       rect    = effect.GetBounds(creator);
            CropEffect effect2 = new CropEffect
            {
                Source          = effect,
                SourceRectangle = new Rect(2, 2, rect.Width - 4, rect.Height - 4),
            };


            //DottedLine
            this.OutPut = new LuminanceToAlphaEffect //Alpha
            {
                Source = new EdgeDetectionEffect     //Edge
                {
                    Amount = 1,
                    Source = effect2
                },
            };
        }
    protected override IEffect[] GetEffects(Transform transform)
    {
        IEffect[] effects = new IEffect[3];

        ScaleEffect scaleEffect = new ScaleEffect();
        Vector3     max         = transform.localScale * 1.2f;

        scaleEffect.Init(transform, max, Vector3.zero, 0.5f, -1, LoopType.Yoyo);
        effects[0] = scaleEffect;

        SlowSpeedEffect ySlow = new SlowSpeedEffect();

        ySlow.Init(transform, Vector2.up, Random.Range(1, 4), Random.Range(2, 4), -10);
        effects[1] = ySlow;

        SlowSpeedEffect xSlow      = new SlowSpeedEffect();
        float           startSpeed = Random.Range(-0.5f, 0.5f);
        float           slowSpeed  = 0;

        if (startSpeed > 0)
        {
            slowSpeed = Random.Range(0.3f, 1);
        }
        else
        {
            slowSpeed = Random.Range(-0.3f, -1);
        }
        xSlow.Init(transform, Vector2.right, startSpeed, slowSpeed, 0);
        effects[2] = xSlow;

        return(effects);
    }
示例#5
0
        public static SoftwareBitmap CropAndResize(this SoftwareBitmap softwareBitmap, Rect bounds, float newWidth, float newHeight)
        {
            var resourceCreator = CanvasDevice.GetSharedDevice();

            using (var canvasBitmap = CanvasBitmap.CreateFromSoftwareBitmap(resourceCreator, softwareBitmap))
                using (var canvasRenderTarget = new CanvasRenderTarget(resourceCreator, newWidth, newHeight, canvasBitmap.Dpi))
                    using (var drawingSession = canvasRenderTarget.CreateDrawingSession())
                        using (var scaleEffect = new ScaleEffect())
                            using (var cropEffect = new CropEffect())
                                using (var atlasEffect = new AtlasEffect())
                                {
                                    drawingSession.Clear(Colors.White);

                                    cropEffect.SourceRectangle = bounds;
                                    cropEffect.Source          = canvasBitmap;

                                    atlasEffect.SourceRectangle = bounds;
                                    atlasEffect.Source          = cropEffect;

                                    scaleEffect.Source = atlasEffect;
                                    scaleEffect.Scale  = new System.Numerics.Vector2(newWidth / (float)bounds.Width, newHeight / (float)bounds.Height);
                                    drawingSession.DrawImage(scaleEffect);
                                    drawingSession.Flush();

                                    return(SoftwareBitmap.CreateCopyFromBuffer(canvasRenderTarget.GetPixelBytes().AsBuffer(), BitmapPixelFormat.Bgra8, (int)newWidth, (int)newHeight, BitmapAlphaMode.Premultiplied));
                                }
        }
示例#6
0
        private async void OnCreateResources(CanvasControl sender, object args)
        {
            if (Image == null)
            {
                return;
            }

            _imageLoaded = false;
            _scaleEffect = new ScaleEffect();
            _blurEffect  = new GaussianBlurEffect();

            var file = Image as StorageFile;

            if (file != null)
            {
                using (var thumbnail = await file.GetThumbnailAsync(ThumbnailMode.VideosView))
                {
                    _image = await CanvasBitmap.LoadAsync(sender.Device, thumbnail);
                }

                _imageLoaded = true;
                sender.Invalidate();
            }

            var url = Image as string;

            if (!string.IsNullOrEmpty(url))
            {
                _image = await CanvasBitmap.LoadAsync(sender.Device, new Uri(url));

                _imageLoaded = true;
                sender.Invalidate();
            }
        }
示例#7
0
    protected override void OnWorkshopUpdateState(bool state, MTK_Interactable current)
    {
        if (state)
        {
            m_scaleEffect = current.GetComponent <ScaleEffect>();

            if (!m_scaleEffect)
            {
                m_scaleEffect = current.gameObject.AddComponent <ScaleEffect>();
                m_scaleEffect.ApplyEffect();
            }

            AkSoundEngine.PostEvent("LFO_Scale_Play", gameObject);
        }
        else
        {
            if (m_scaleEffect)
            {
                m_scaleEffect.RemoveEffect();
            }

            m_scaleEffect = null;

            AkSoundEngine.PostEvent("LFO_Scale_Stop", gameObject);
        }
    }
示例#8
0
        public async Task SetCanvas(double width, double height, IRandomAccessStream randomAccessStream)
        {
            CanvasVisibility = Visibility.Visible;

            canvasControl.Height = height;
            canvasControl.Width  = width;

            canvasBitmap = await CanvasBitmap.LoadAsync(canvasControl, randomAccessStream);

            //CanvasDevice device = CanvasDevice.GetSharedDevice();
            //CanvasRenderTarget offscreen = new CanvasRenderTarget(device, (float)width/2,(float)height/2,96);
            if (PictureCompression.UsePictureCompression)
            {
                ScaleEffect effect = new ScaleEffect()
                {
                    Source = canvasBitmap,
                    Scale  = new Vector2((float)(160 / width))
                };
                CanvasDevice       device    = CanvasDevice.GetSharedDevice();
                CanvasRenderTarget offscreen = new CanvasRenderTarget(device, (float)160, (float)(height * 160 / width), 96);
                using (CanvasDrawingSession ds = offscreen.CreateDrawingSession())
                {
                    ds.Clear(Colors.Black);
                    ds.DrawImage(effect);
                }
                canvasControl.Height = offscreen.Size.Height;
                canvasControl.Width  = offscreen.Size.Width;
                canvasBitmap         = offscreen;
            }
            canvasControl.Invalidate();
            ASCIIText   = string.Empty;
            BitmapImage = new BitmapImage();
        }
        public CanvasBitmap GenerateThumbnail()
        {
            if (canvasBitmap == null)
            {
                if (parent != null)
                    parent.StartWritingOutput("Canvas Bitmap is null. Load a Photo.", 1);

                return null;
            }
            
            CanvasRenderTarget canvasRenderTargetThumbnail = new CanvasRenderTarget(CanvasDevice.GetSharedDevice(), (float)thumbnailSize, (float)thumbnailSize, canvasBitmap.Dpi);

            //if (parent != null)
            //    parent.StartWritingOutput("Creating Thumbnail : Dimensions: " + thumbnailSize.ToString() + " x " + thumbnailSize.ToString(), 1);

            int ww = (int)canvasBitmap.SizeInPixels.Width;
            int hh = (int)canvasBitmap.SizeInPixels.Height;

            double newww = ww;
            double newhh = hh;
            double offsetx = 0;
            double offsety = 0;
            double unscaledHeight = hh;
            double referenceHeight = thumbnailSize;

            //make a square
            if (ww > hh)
            {
                newww = hh;
                offsetx = (ww - hh) / 2.0;
                unscaledHeight = hh;
            }
            else
            {
                newhh = ww;
                offsety = (hh - ww) / 2.0;
                unscaledHeight = ww;
            }

            if (unscaledHeight<=0.1)
            {
                if (parent != null)
                    parent.StartWritingOutput("Error making thumbnail :  Invalid unscaled height. ", 1);

            }

            double scaleFactor = referenceHeight / (double)unscaledHeight;
            //if (scaleFactor < 1.0) //can be greater or smaller than 1
            
            using (var session = canvasRenderTargetThumbnail.CreateDrawingSession())
            {
                ScaleEffect scaleEffect = new ScaleEffect();
                scaleEffect.Source = canvasBitmap;
                scaleEffect.Scale = new System.Numerics.Vector2((float)scaleFactor, (float)scaleFactor);
                session.DrawImage(scaleEffect);
            }

            return canvasRenderTargetThumbnail;

        }
 private async Task ReflashBackground(CanvasAnimatedControl resource, string imgPath)
 {
     if (imgPath == null)
     {
         return;
     }
     if (imgbackground == null || oldImgPath != imgPath)
     {
         oldImgPath    = imgPath;
         imgbackground = await CanvasBitmap.LoadAsync(resource, new Uri(imgPath), 96);
     }
     if (blurEffect == null)
     {
         blurEffect = new GaussianBlurEffect()
         {
             BlurAmount   = 40.0f,
             BorderMode   = EffectBorderMode.Soft,
             Optimization = EffectOptimization.Speed
         };
     }
     blurEffect.Source = imgbackground;
     if (scaleEffect == null)
     {
         scaleEffect = new ScaleEffect()
         {
             CenterPoint = new System.Numerics.Vector2()
         };
     }
     scaleEffect.Source = blurEffect;
     scaleEffect.Scale  = new System.Numerics.Vector2(await ComputeScaleFactor());
     resource.Paused    = false;
 }
示例#11
0
        public static ICanvasImage ScaleImage(ICanvasImage image)
        {
            var scaleEffect = new ScaleEffect
            {
                Source = image,
                Scale  = new Vector2((float)Scale, (float)Scale)
            };

            return(scaleEffect);
        }
示例#12
0
        public void ProcessFrame(ProcessVideoFrameContext context)
        {
            bool skipMaskPred = false;

            if (context.InputFrame.IsDiscontinuous)
            {
                streamStartDelta = TimeSpan.FromTicks(DateTime.Now.Ticks) - context.InputFrame.SystemRelativeTime.Value;
            }
            else
            {
                if ((TimeSpan.FromTicks(DateTime.Now.Ticks) - context.InputFrame.SystemRelativeTime.Value - streamStartDelta) > TimeSpan.FromMilliseconds(maxDelay))
                {
                    skipMaskPred = true;
                }
            }

            if (!skipMaskPred)
            {
                frameCount++;
                features["0"] = context.InputFrame;
                var resTask   = _learningModel.EvaluateFeaturesAsync(features, string.Empty).AsTask();
                var startTime = DateTime.Now.Ticks;
                resTask.Wait();
                Debug.WriteLine("delta {0}", TimeSpan.FromTicks(DateTime.Now.Ticks - startTime));
            }

            using (CanvasBitmap inputBitmap = CanvasBitmap.CreateFromDirect3D11Surface(canvasDevice, context.InputFrame.Direct3DSurface))
                using (CanvasBitmap inputMask = CanvasBitmap.CreateFromDirect3D11Surface(canvasDevice, output.Direct3DSurface))
                    using (CanvasRenderTarget renderTarget = CanvasRenderTarget.CreateFromDirect3D11Surface(canvasDevice, context.OutputFrame.Direct3DSurface))
                        using (CanvasDrawingSession ds = renderTarget.CreateDrawingSession())
                        {
                            ds.Clear(Colors.Green);

                            var addAlpha = new ColorMatrixEffect()
                            {
                                Source      = inputMask,
                                ColorMatrix = RToAlpha
                            };

                            var resize = new ScaleEffect()
                            {
                                Source = addAlpha,
                                Scale  = new Vector2(((float)inputBitmap.SizeInPixels.Width / inputMask.SizeInPixels.Width), ((float)inputBitmap.SizeInPixels.Height / inputMask.SizeInPixels.Height))
                            };

                            var blend = new AlphaMaskEffect()
                            {
                                Source    = inputBitmap,
                                AlphaMask = resize
                            };

                            ds.DrawImage(blend);
                            ds.DrawText(String.Format("FPS: {0:f1}", currentFPS), fpsLabelOffset, fpsLabelColor);
                        }
        }
        //make a small size bitmap for preview / effects modification purposes
        public void CreatePreviewBitmap()
        {
            double referenceHeight = 800;
            if (canvasBitmap != null)
            {
                int ww = (int)canvasBitmap.SizeInPixels.Width;
                int hh = (int)canvasBitmap.SizeInPixels.Height;

                double newww = ww;
                double newhh = hh;

                double widthToHeightRatio = 1.0;
                if (hh > 0)
                    widthToHeightRatio = ww / (double)hh;
                double scaleFactor = referenceHeight / (double)hh;
                if (scaleFactor<1.0)
                {
                        newww = scaleFactor * ww;
                        newhh = referenceHeight;
                }


                if (scaleFactor >= 1.0)
                {
                    if (parent != null)
                        parent.StartWritingOutput("Using original canvasBitmap due to its small size: Dimensions: " + newww.ToString() + " x " + newhh.ToString(), 1);

                    if (canvasRenderTargetPreview != null)
                        canvasRenderTargetPreview.Dispose();

                    canvasRenderTargetPreview = null;

                    return;
                }

                if (canvasRenderTargetPreview != null)
                    canvasRenderTargetPreview.Dispose();

                canvasRenderTargetPreview = new CanvasRenderTarget(CanvasDevice.GetSharedDevice(), (float) newww, (float) newhh, canvasBitmap.Dpi);

                if (parent != null)
                    parent.StartWritingOutput("Creating canvasRenderTargetPreview : Dimensions: " + newww.ToString() + " x " + newhh.ToString(), 1);

                using (var session = canvasRenderTargetPreview.CreateDrawingSession())
                {
                    ScaleEffect scaleEffect = new ScaleEffect();                    
                    scaleEffect.Source = canvasBitmap;
                    scaleEffect.Scale = new System.Numerics.Vector2((float)scaleFactor, (float)scaleFactor);
                    session.DrawImage(scaleEffect);
                }


            }

        }
示例#14
0
 public CanvasImg(string source)
 {
     Src               = source;
     Opacity           = 0;
     GaussianBlurCache = new GaussianBlurEffect()
     {
         BlurAmount = 4.0f,
         BorderMode = EffectBorderMode.Soft
     };
     ScaleEffect = new ScaleEffect()
     {
         CenterPoint = new System.Numerics.Vector2(0, 0)
     };
 }
示例#15
0
 public static SoftwareBitmap Resize(SoftwareBitmap softwareBitmap, float newWidth, float newHeight)
 {
     using (var resourceCreator = CanvasDevice.GetSharedDevice())
         using (var canvasBitmap = CanvasBitmap.CreateFromSoftwareBitmap(resourceCreator, softwareBitmap))
             using (var canvasRenderTarget = new CanvasRenderTarget(resourceCreator, newWidth, newHeight, canvasBitmap.Dpi))
                 using (var drawingSession = canvasRenderTarget.CreateDrawingSession())
                     using (var scaleEffect = new ScaleEffect())
                     {
                         scaleEffect.Source = canvasBitmap;
                         scaleEffect.Scale  = new System.Numerics.Vector2(newWidth / softwareBitmap.PixelWidth, newHeight / softwareBitmap.PixelHeight);
                         drawingSession.DrawImage(scaleEffect);
                         drawingSession.Flush();
                         return(SoftwareBitmap.CreateCopyFromBuffer(canvasRenderTarget.GetPixelBytes().AsBuffer(), BitmapPixelFormat.Bgra8, (int)newWidth, (int)newHeight, BitmapAlphaMode.Premultiplied));
                     }
 }
示例#16
0
        async Task ShowBitmapOnTargetAsync(CanvasBitmap bitmap)
        {
            int scale = (int)Math.Ceiling(ActualSize.Y / bitmap.Size.Height);

            Height = bitmap.Size.Height / bitmap.Size.Width * ActualSize.X;

            _previousBitmap = bitmap;
            _previousColors = null;

            var compositor = ElementCompositionPreview.GetElementVisual(this).Compositor;
            var compositionGraphicsDevice = CanvasComposition.CreateCompositionGraphicsDevice(compositor, CanvasDevice.GetSharedDevice());

            if (_patternBitmap is null)
            {
                _patternBitmap = await CanvasBitmap.LoadAsync(CanvasDevice.GetSharedDevice(), @"Assets\BackgroundPattern.png");
            }

            var surface = compositionGraphicsDevice.CreateDrawingSurface(
                new Size(bitmap.Size.Width * scale, bitmap.Size.Height * scale),
                DirectXPixelFormat.B8G8R8A8UIntNormalized,
                DirectXAlphaMode.Premultiplied);

            using (var drawingSession = CanvasComposition.CreateDrawingSession(surface))
            {
                var border = new BorderEffect
                {
                    ExtendX = CanvasEdgeBehavior.Wrap,
                    ExtendY = CanvasEdgeBehavior.Wrap,
                    Source  = _patternBitmap,
                };

                var scaleEffect = new ScaleEffect
                {
                    Scale             = new Vector2(scale, scale),
                    InterpolationMode = CanvasImageInterpolation.NearestNeighbor,
                };

                scaleEffect.Source = border;
                drawingSession.DrawImage(scaleEffect);
                scaleEffect.Source = bitmap;
                drawingSession.DrawImage(scaleEffect);
            }

            var surfaceBrush = compositor.CreateSurfaceBrush(surface);

            _spriteVisual.Brush = surfaceBrush;
        }
        /// <summary>
        /// Constructs a high pass effect with the specified parameters.
        /// </summary>
        /// <param name="kernelSize">The size of the filter kernel. A larger size preserves more of lower frequencies.</param>
        /// <param name="isGrayscale">True if the highpass effect should give a grayscale result. Otherwise the individual R, G, B channels are treated separately.</param>
        /// <param name="downscaleDivisor">How much to downscale the image to reduce the cost of the internal blur operation, trading speed for some fidelity. Suitable value depends on the kernelSize.</param>
        public HighpassEffect(uint kernelSize, bool isGrayscale = false, uint downscaleDivisor = 1)
        {
            m_kernelSize       = kernelSize;
            m_downscaleDivisor = downscaleDivisor;
            m_isGrayscale      = isGrayscale;

            if (m_downscaleDivisor > 1)
            {
                m_downscaleEffect        = new ScaleEffect(/*source*/ 1.0 / m_downscaleDivisor);
                m_downscaleCachingEffect = new CachingEffect(m_downscaleEffect);

                int blurKernelSize = Math.Max(1, (int)(3.0 * m_kernelSize / m_downscaleDivisor));

                m_blurEffect = new BlurEffect(m_downscaleCachingEffect)
                {
                    KernelSize = blurKernelSize
                };

                m_highPassBlendEffect = new BlendEffect(/*source*/)
                {
                    ForegroundSource = m_blurEffect,
                    BlendFunction    = BlendFunction.SignedDifference
                };
            }
            else
            {
                int blurKernelSize = Math.Max(1, (int)(3.0 * m_kernelSize));

                m_blurEffect = new BlurEffect()
                {
                    KernelSize = blurKernelSize
                };

                m_highPassBlendEffect = new BlendEffect(/*source*/)
                {
                    ForegroundSource = m_blurEffect,
                    BlendFunction    = BlendFunction.SignedDifference
                };
            }

            if (m_isGrayscale)
            {
                m_highPassGrayscaleEffect = new GrayscaleEffect(m_highPassBlendEffect);
            }
        }
示例#18
0
        public void LiquifyFill(ICanvasResourceCreator rc, CanvasBitmap cb)//填充一个位图
        {
            Liquify = new CanvasCommandList(rc);

            using (var ds = Liquify.CreateDrawingSession())
            {
                //画渐变圆形
                CanvasRadialGradientBrush brush = PaintBrush(rc, new Vector2(LiquifySize), LiquifySize, 0, LiquifyAmount / 100, LiquifyColor);
                ds.FillCircle(LiquifySize, LiquifySize, LiquifySize, brush);

                //画位图
                ScaleEffect se = new ScaleEffect
                {
                    Source = cb,
                    Scale  = new Vector2(LiquifySize * 2 / (float)cb.Size.Width)
                };
                ds.DrawImage(se, 0, 0, new Rect(0, 0, LiquifySize * 2, LiquifySize * 2), 1, CanvasImageInterpolation.Linear, CanvasComposite.SourceIn);
            }
        }
示例#19
0
        private void ThumbnailButton_Tapped(object sender, TappedRoutedEventArgs e)
        {
            CanvasRenderTarget Thumbnail = new CanvasRenderTarget(App.Model.VirtualControl, ThumbnailWidth, ThumbnailHeight);

            using (var ds = Thumbnail.CreateDrawingSession())
            {
                var space = App.Setting.PaintSpace * (float)Math.Sqrt(App.Setting.PaintWidth);
                for (float x = 10; x < ThumbnailWidth - 10; x += space)
                {
                    //根据画布的X位置,求Sin高度角度(一条上下弧线)
                    var   sinh = x / ThumbnailWidth * Math.PI * 2;
                    float h    = 20 * (float)Math.Sin(sinh);//上下浮动

                    //根据画布的X位置,求Sin大小角度(一个上凸曲线)
                    var         sins = x / ThumbnailWidth * Math.PI;
                    Vector2     s    = new Vector2((float)Math.Sin(sins));//大小浮动
                    ScaleEffect se   = new ScaleEffect {
                        Source = App.Setting.PaintShow, Scale = s
                    };

                    ds.DrawImage(se, x, (float)ThumbnailHeight / 2 + h);
                }
            }

            string ss = "-" + (App.Setting.PaintWidth).ToString() + "-" + (App.Setting.PaintHard).ToString() + "-" + (App.Setting.PaintOpacity).ToString() + "-" + (App.Setting.PaintSpace).ToString();

            byte[] bytes = Thumbnail.GetPixelBytes();
            修图.Library.Image.SavePng(KnownFolders.SavedPictures, bytes, ThumbnailWidth, ThumbnailHeight, ss);

            string path = "Icon/Clutter/OK.png";

            修图.Library.Toast.ShowToastNotification(path, "已保存到本地相册");



            App.Tip(ss);//全局提示

            DataPackage dataPackage = new DataPackage();

            dataPackage.SetText(ss);
            Clipboard.SetContent(dataPackage);
        }
示例#20
0
        internal virtual void drawImage(CanvasBitmap canvasBitmap, int x, int y, int w, int h)
        {
            ScaleEffect scale = new ScaleEffect()
            {
                Source = canvasBitmap,
                Scale  = new Vector2()
                {
                    X = ((float)w) / canvasBitmap.SizeInPixels.Width,
                    Y = ((float)h) / canvasBitmap.SizeInPixels.Height
                }
            };

            if (isMutable())
            {
                graphics.DrawImage(image2Premultiply(scale), x, y);
            }
            else
            {
                graphics.DrawImage(scale, x, y);
            }
        }
        /// <summary>
        /// Constructs a high pass effect with the specified parameters.
        /// </summary>
        /// <param name="kernelSize">The size of the filter kernel. A larger size preserves more of lower frequencies.</param>
        /// <param name="isGrayscale">True if the highpass effect should give a grayscale result. Otherwise the individual R, G, B channels are treated separately.</param>
        /// <param name="downscaleDivisor">How much to downscale the image to reduce the cost of the internal blur operation, trading speed for some fidelity. Suitable value depends on the kernelSize.</param>
        public HighpassEffect(uint kernelSize, bool isGrayscale = false, uint downscaleDivisor = 1)
        {
            m_kernelSize = kernelSize;
            m_downscaleDivisor = downscaleDivisor;
            m_isGrayscale = isGrayscale;
            
            if (m_downscaleDivisor > 1)
            {
                m_downscaleEffect = new ScaleEffect(/*source*/ 1.0 / m_downscaleDivisor);
                m_downscaleCachingEffect = new CachingEffect(m_downscaleEffect);

                int blurKernelSize = Math.Max(1, (int)(3.0 * m_kernelSize / m_downscaleDivisor));

                m_blurEffect = new BlurEffect(m_downscaleCachingEffect) { KernelSize = blurKernelSize };

                m_highPassBlendEffect = new BlendEffect( /*source*/)
                {
                    ForegroundSource = m_blurEffect,
                    BlendFunction = BlendFunction.SignedDifference
                };
            }
            else
            {
                int blurKernelSize = Math.Max(1, (int)(3.0 * m_kernelSize));

                m_blurEffect = new BlurEffect() { KernelSize = blurKernelSize };

                m_highPassBlendEffect = new BlendEffect( /*source*/)
                {
                    ForegroundSource = m_blurEffect,
                    BlendFunction = BlendFunction.SignedDifference
                };
            }
                 
            if (m_isGrayscale)
            {
                m_highPassGrayscaleEffect = new GrayscaleEffect(m_highPassBlendEffect);
            }
        }
示例#22
0
        private void CreateScaleEffectSettings()
        {
            switch (ScaleSettings)
            {
            case ScaleSettings.Fill:
                _scaleX = Width / _imageProperties.PixelWidth;
                _scaleY = Height / _imageProperties.PixelHeight;
                break;

            case ScaleSettings.None:
                _scaleX = 1;
                _scaleY = 1;
                break;

            case ScaleSettings.Scale:
                if (double.IsNaN(Height) && double.IsNaN(Width))
                {
                    _scaleX = 1;
                    _scaleY = 1;
                    Height  = _imageProperties.PixelHeight;
                    Width   = _imageProperties.PixelWidth;
                }
                else
                {
                    var tempScaleY  = double.IsNaN(Height) ? 1.0 : (Height / _imageProperties.PixelHeight);
                    var tempScaleX  = double.IsNaN(Width) ? 1.0 : (Width / _imageProperties.PixelWidth);
                    var lowestRatio = Math.Min(tempScaleX, tempScaleY);
                    _scaleX = lowestRatio;
                    _scaleY = lowestRatio;
                    Height  = tempScaleY > tempScaleX ? lowestRatio * _imageProperties.PixelHeight : Height;
                    Width   = tempScaleX > tempScaleY ? lowestRatio * _imageProperties.PixelWidth : Width;
                }

                break;
            }

            _scaleEffect = new ScaleEffect();
        }
示例#23
0
        //方法:设置(写到创建资源事件里)
        public void Set(ICanvasResourceCreator rc, float sx, float sy, ICanvasImage ci)
        {
            //放大
            ScaleEffect se = new ScaleEffect
            {
                Source            = ci,
                Scale             = new Vector2(1 / sx, 1 / sy),
                InterpolationMode = CanvasImageInterpolation.NearestNeighbor,
            };

            //剪裁四周的边线
            var        rect = se.GetBounds(rc);
            CropEffect sce  = new CropEffect
            {
                Source          = se,
                SourceRectangle = new Rect(2, 2, rect.Width - 4, rect.Height - 4),
            };

            //恢复正常大小
            CanvasCommandList ccl = new CanvasCommandList(rc);

            using (var ds = ccl.CreateDrawingSession())
            {
                ds.Clear(Colors.Transparent);
                ds.DrawImage(sce);
            }

            //变成线框
            Image = new LuminanceToAlphaEffect   //亮度转不透明度
            {
                Source = new EdgeDetectionEffect //边缘检测
                {
                    Amount = 1,
                    Source = ccl
                },
            };
        }
示例#24
0
        ICanvasImage GetSelectionBorder(ICanvasImage mask, float zoomFactor)
        {
            // Scale so our border will always be the same width no matter how the image is zoomed.
            var scaleToCurrentZoom = new ScaleEffect
            {
                Source = mask,
                Scale  = new Vector2(zoomFactor)
            };

            // Find edges of the selection.
            var detectEdges = new EdgeDetectionEffect
            {
                Source = scaleToCurrentZoom,
                Amount = 0.1f
            };

            // Colorize.
            var colorItMagenta = new ColorMatrixEffect
            {
                Source = detectEdges,

                ColorMatrix = new Matrix5x4
                {
                    M11 = 1,
                    M13 = 1,
                    M14 = 1,
                }
            };

            // Scale back to the original size.
            return(new ScaleEffect
            {
                Source = colorItMagenta,
                Scale = new Vector2(1 / zoomFactor)
            });
        }
示例#25
0
        public void Draw(CanvasAnimatedDrawEventArgs args)
        {
            if (currentImg == null)
            {
                return;
            }

            if (currentImg.GaussianBlurCache == null)
            {
                currentImg.GaussianBlurCache = new GaussianBlurEffect()
                {
                    Source       = currentImg.Bmp,
                    BlurAmount   = 1.0f,
                    Optimization = EffectOptimization.Speed
                };
            }

            if (currentImg.Width > MetroSlideshow.WindowWidth)
            {
                currentImg.Scale = (float)(MetroSlideshow.WindowHeight / currentImg.Height);
            }
            else
            {
                currentImg.Scale = (float)(MetroSlideshow.WindowWidth / currentImg.Width);
            }
            if (frame <= 900)
            {
                if (frame == 0)
                {
                    // Set Default values
                    currentImg.Opacity = 0;
                }
                else if (frame < 200)
                {
                }
                zoom += 0.0001f;
            }
            else if (frame < 1000)
            {
                zoom += 0.005f;
            }

            var scaleEffect = new ScaleEffect()
            {
                Source = currentImg.GaussianBlurCache,
                Scale  = new Vector2()
                {
                    X = currentImg.Scale + zoom,
                    Y = currentImg.Scale + zoom
                },
            };

            scaleEffect.CenterPoint = new Vector2()
            {
                X = 0,
                Y = 0
            };

            if (frame < 200)
            {
                currentImg.Opacity += 0.002f;
            }
            else if (frame > 900)
            {
                currentImg.Opacity -= 0.003f;
            }

            args.DrawingSession.DrawImage(scaleEffect, new Vector2(), new Rect()
            {
                Height = MetroSlideshow.WindowHeight,
                Width  = MetroSlideshow.WindowWidth
            }, currentImg.Opacity);

            //args.DrawingSession.DrawText("COLDPLAY", new Vector2()
            //{
            //    X = x,
            //    Y = (float)(MetroSlideshow.WindowHeight / 2)
            //}, col, texts[0].TextForm);

            //args.DrawingSession.DrawText("clocks", new Vector2()
            //{
            //    X = (float)(MetroSlideshow.WindowWidth / 2),
            //    Y = y
            //}, col, texts[0].TextForm);

            //args.DrawingSession.DrawText(frame.ToString(), new Vector2(), col, texts[0].TextForm);
            x = x + 2;
            y++;
            threshold++;
            if (threshold == 1)
            {
                threshold = 0;
                frame++;
            }
            if (frame == 1200)
            {
                // Resetting variables
                if (ImgIndex < Imgs.Count - 1)
                {
                    ImgIndex++;
                }
                else
                {
                    ImgIndex = 0;
                }
                frame = 0;
                zoom  = 0;
            }
        }
示例#26
0
        public async void Update(ICanvasAnimatedControl sender, CanvasAnimatedUpdateEventArgs args)
        {
            try
            {
                if (currentImg == null)
                {
                    return;
                }

                if (!currentImg.Loaded)
                {
                    await currentImg.Initialize(sender);
                }

                bool computeBlurPic = true;
                if (frame < IntroFrameThreshold)
                {
                    if (frame == 0)
                    {
                        // Set Default values
                        currentImg.Opacity = 0;
                        blurAmount         = MaximumBlur;
                    }

                    blurAmount -= 0.025f;
                }
                else if (frame <= OutroFrameThreshold)
                {
                    if (currentImg.GaussianBlurCache != null)
                    {
                        computeBlurPic = false;
                    }
                }
                else if (frame < 1000)
                {
                    blurAmount += 0.025f;
                }

                if (computeBlurPic)
                {
                    if (currentImg.Bmp == null)
                    {
                        return;
                    }
                    if (blurAmount < 10)
                    {
                        currentImg.GaussianBlurCache = new GaussianBlurEffect()
                        {
                            Source       = currentImg.Bmp,
                            BlurAmount   = blurAmount,
                            Optimization = EffectOptimization.Speed
                        };
                    }
                    else
                    {
                    }
                }

                float screenRatio = (float)MetroSlideshow.WindowWidth / (float)MetroSlideshow.WindowHeight;
                float imgRatio    = (float)currentImg.Width / (float)currentImg.Height;
                if (currentImg.Width == -1 || currentImg.Height == -1)
                {
                    return;
                }
                if (imgRatio > screenRatio)
                {
                    //img wider than screen, need to scale horizontally
                    currentImg.Scale = (float)(MetroSlideshow.WindowHeight / currentImg.Height);
                }
                else
                {
                    currentImg.Scale = (float)(MetroSlideshow.WindowWidth / currentImg.Width);
                }



                // "Vector2" requires System.Numerics for UWP. But for some reason ScaleEffect can only use Windows.Foundation.Numerics,
                // which you can't use to make vectors. So... we can't use this yet until we can figure out what's wrong here.
                if (currentImg.GaussianBlurCache == null)
                {
                    return;
                }

                var saturationEffect = new SaturationEffect()
                {
                    Source     = currentImg.GaussianBlurCache,
                    Saturation = 1f,
                };
                var scaleEffect = new ScaleEffect()
                {
                    Source = saturationEffect,
                    Scale  = new System.Numerics.Vector2()
                    {
                        X = currentImg.Scale,
                        Y = currentImg.Scale
                    },
                };

                scaleEffect.CenterPoint = new System.Numerics.Vector2()
                {
                    X = 0, Y = 0
                };

                currentImg.ScaleEffect = scaleEffect;

                if (frame < IntroFrameThreshold)
                {
                    currentImg.Opacity += 0.0020f;
                }
                else if (frame > OutroFrameThreshold)
                {
                    var decrease = 0.0027f;
                    if (fastChange)
                    {
                        currentImg.Opacity -= decrease * 4;
                    }
                    else
                    {
                        currentImg.Opacity -= decrease;
                    }
                }
            }
            catch { }
        }
        public void DrawBitmap(CanvasControl drawingcanvas, CanvasDrawingSession session)
        {
            if (canvasBitmap != null)
            {
                try
                {
                    int ww = (int)canvasBitmap.SizeInPixels.Width;
                    int hh = (int)canvasBitmap.SizeInPixels.Height;

                    //Using Preview Size
                    if (canvasRenderTargetPreview != null)
                    {
                        ww = (int) canvasRenderTargetPreview.SizeInPixels.Width;
                        hh = (int)canvasRenderTargetPreview.SizeInPixels.Height;
                        
                    }
                    
                    double widthToHeightRatio = 1.0;
                    if (hh > 0)
                        widthToHeightRatio = ww / (double)hh;
                    double scaleFactor = (double)drawingcanvas.Height / (double)hh;

                    
                    //byte[] bb = canvasBitmap.GetPixelBytes(0, 0, ww, hh);
                    Rect rect = new Rect(0, 0, ww, hh);

                    //if (parent != null)
                    //    parent.StartWritingOutput("PixelSize : " + ww.ToString() + " x " + hh.ToString(), 1);
                    

                    ScaleEffect scaleEffect = new ScaleEffect();
                    if (canvasRenderTarget != null)
                    {
                        scaleEffect.Source = canvasRenderTarget;
                        //if (parent != null)
                        //    parent.StartWritingOutput("Draw using canvasRenderTarget", 1);
                    }
                    else if (canvasRenderTargetPreview != null)
                    {
                        //ver 0.71
                        scaleEffect.Source = canvasRenderTargetPreview;
                        if (parent != null)
                            parent.StartWritingOutput("Draw using canvasRenderTargetPreview", 1);
                    }
                    else
                    {
                        if (parent != null)
                            parent.StartWritingOutput("Draw using canvasBitmap", 1);
                        scaleEffect.Source = canvasBitmap;

                    }
                    scaleEffect.Scale = new System.Numerics.Vector2((float)scaleFactor, (float)scaleFactor);

                    double actualCanvasWdith = drawingcanvas.ActualWidth;
                    double offsetx = (actualCanvasWdith - (scaleFactor * ww)) / 2.0;
                    double offsety = 0;
                    
                    //args.DrawingSession.DrawImage(simplePhotoEditor.canvasBitmap);                    
                    session.DrawImage(scaleEffect, (float)offsetx, (float)offsety);
                }
                catch (Exception e)
                {
                    if (parent != null)
                        parent.StartWritingOutput("Draw Error : " + e.Message, 1);

                }
            }


        }
示例#28
0
        private void ProcessFrame(Direct3D11CaptureFrame frame)
        {
            // Resize and device-lost leverage the same function on the
            // Direct3D11CaptureFramePool. Refactoring it this way avoids
            // throwing in the catch block below (device creation could always
            // fail) along with ensuring that resize completes successfully and
            // isn’t vulnerable to device-lost.
            bool needsReset     = false;
            bool recreateDevice = false;

            if ((frame.ContentSize.Width != _lastSize.Width) ||
                (frame.ContentSize.Height != _lastSize.Height))
            {
                needsReset = true;
                _lastSize  = frame.ContentSize;
                _swapChain.ResizeBuffers(_lastSize.Width, _lastSize.Height);
            }
            Direct3D11CaptureFrame direct = frame;

            try
            {
                // Take the D3D11 surface and draw it into a
                // Composition surface.
                if (direct.SystemRelativeTime - lastFrameTime < TimeSpan.FromSeconds(1))
                {
                    //F**k Microsoft🤬
                    MediaClip mediaClip = MediaClip.CreateFromSurface(direct.Surface, direct.SystemRelativeTime - lastFrameTime);
                    composition.Clips.Add(mediaClip);
                }
                lastFrameTime = direct.SystemRelativeTime;

                // Convert our D3D11 surface into a Win2D object.
                canvasBitmap = CanvasBitmap.CreateFromDirect3D11Surface(
                    _canvasDevice,
                    direct.Surface);

                using (var drawingSession = _swapChain.CreateDrawingSession(Colors.Transparent))
                {
                    //drawingSession.DrawCircle(400, 300, 100, Colors.Red, 20);
                    ScaleEffect effect = new ScaleEffect()
                    {
                        Source = canvasBitmap,
                        Scale  = new Vector2((float)swapChain.ActualWidth / _item.Size.Width)
                    };

                    drawingSession.DrawImage(effect);
                }

                _swapChain.Present();

                //canvasControl.Invalidate();
                // Helper that handles the drawing for us, not shown.
            }
            // This is the device-lost convention for Win2D.
            catch (Exception e) when(_canvasDevice.IsDeviceLost(e.HResult))
            {
                // We lost our graphics device. Recreate it and reset
                // our Direct3D11CaptureFramePool.
                needsReset     = true;
                recreateDevice = true;
            }
            if (needsReset)
            {
                ResetFramePool(direct.ContentSize, recreateDevice);
            }
        }
示例#29
0
        ICanvasImage GetSelectionBorder(ICanvasImage mask, float zoomFactor)
        {
            // Scale so our border will always be the same width no matter how the image is zoomed.
            var scaleToCurrentZoom = new ScaleEffect
            {
                Source = mask,
                Scale = new Vector2(zoomFactor)
            };

            // Find edges of the selection.
            var detectEdges = new EdgeDetectionEffect
            {
                Source = scaleToCurrentZoom,
                Amount = 0.1f
            };

            // Colorize.
            var colorItMagenta = new ColorMatrixEffect
            {
                Source = detectEdges,

                ColorMatrix = new Matrix5x4
                {
                    M11 = 1,
                    M13 = 1,
                    M14 = 1,
                }
            };

            // Scale back to the original size.
            return new ScaleEffect
            {
                Source = colorItMagenta,
                Scale = new Vector2(1 / zoomFactor)
            };
        }
示例#30
0
        public void Draw(CanvasAnimatedDrawEventArgs args)
        {
            if (currentImg == null) return;

            if (currentImg.GaussianBlurCache == null)
            {
                currentImg.GaussianBlurCache = new GaussianBlurEffect()
                {
                    Source = currentImg.Bmp,
                    BlurAmount = 1.0f,
                    Optimization = EffectOptimization.Speed
                };
            }

            if (frame <= OutroFrameThreshold)
            {
                if (frame == 0)
                {
                    // Set Default values
                    currentImg.Opacity = 0;
                }
                if (_richAnimations)
                    zoom += 0.0001f;
            }
            else if (frame < 1000)
            {
                if (_richAnimations)
                    zoom += 0.005f;
            }

            float screenRatio = (float)MetroSlideshow.WindowWidth / (float)MetroSlideshow.WindowHeight;
            float imgRatio = (float)currentImg.Width / (float)currentImg.Height;
            if (imgRatio > screenRatio)
            {
                //img wider than screen, need to scale horizontally
                currentImg.Scale = (float)(MetroSlideshow.WindowHeight / currentImg.Height);
            }
            else
            {
                currentImg.Scale = (float)(MetroSlideshow.WindowWidth / currentImg.Width);
            }

            var scaleEffect = new ScaleEffect()
            {
                Source = currentImg.GaussianBlurCache,
                Scale = new Vector2()
                {
                    X = currentImg.Scale + zoom,
                    Y = currentImg.Scale + zoom
                },
            };

            scaleEffect.CenterPoint = new Vector2()
            {
                X = 0,
                Y = 0
            };

            if (frame < IntroFrameThreshold)
            {
                currentImg.Opacity += 0.0016f;
            }
            else if (frame > OutroFrameThreshold)
            {
                currentImg.Opacity -= 0.0027f;
            }

            var txts = Texts.ToList();
            foreach (var text in txts)
            {
                text.Draw(ref args, ref txts);
            }

            args.DrawingSession.DrawImage(scaleEffect, new Vector2(), new Rect()
            {
                Height = MetroSlideshow.WindowHeight,
                Width = MetroSlideshow.WindowWidth
            }, currentImg.Opacity);

            x = x + 2;
            y++;

            threshold++;

            if (threshold == 1)
            {
                threshold = 0;
                frame++;
            }
            if (frame == EndFrameThreshold)
            {
                // Resetting variables
                if (ImgIndex < Imgs.Count - 1)
                {
                    ImgIndex++;
                }
                else
                {
                    ImgIndex = 0;
                }
                frame = 0;
                zoom = 0;
            }
        }
        private void CreateScaleEffectSettings()
        {
            switch (ScaleSettings)
            {
                case ScaleSettings.Fill:
                    _scaleX = Width / _imageProperties.PixelWidth;
                    _scaleY = Height / _imageProperties.PixelHeight;
                    break;
                case ScaleSettings.None:
                    _scaleX = 1;
                    _scaleY = 1;
                    break;
                case ScaleSettings.Scale:
                    if (double.IsNaN(Height) && double.IsNaN(Width))
                    {
                        _scaleX = 1;
                        _scaleY = 1;
                        Height = _imageProperties.PixelHeight;
                        Width = _imageProperties.PixelWidth;
                    }
                    else
                    {
                        var tempScaleY = double.IsNaN(Height) ? 1.0 : (Height / _imageProperties.PixelHeight);
                        var tempScaleX = double.IsNaN(Width) ? 1.0 : (Width / _imageProperties.PixelWidth);
                        var lowestRatio = Math.Min(tempScaleX, tempScaleY);
                        _scaleX = lowestRatio;
                        _scaleY = lowestRatio;
                        Height = tempScaleY > tempScaleX ? lowestRatio * _imageProperties.PixelHeight : Height;
                        Width = tempScaleX > tempScaleY ? lowestRatio * _imageProperties.PixelWidth : Width;
                    }

                    break;
            }

            _scaleEffect = new ScaleEffect();
        }
        //private bool correctionFlag = false;

        public void ProcessFrame(ProcessVideoFrameContext context)
        {
            using (CanvasBitmap inputBitmap = CanvasBitmap.CreateFromDirect3D11Surface(_canvasDevice, context.InputFrame.Direct3DSurface))
                using (CanvasRenderTarget renderTarget = CanvasRenderTarget.CreateFromDirect3D11Surface(_canvasDevice, context.OutputFrame.Direct3DSurface))
                    using (CanvasDrawingSession ds = renderTarget.CreateDrawingSession())
                        using (var scaleEffect = new ScaleEffect())
                            using (CanvasSolidColorBrush solidColorBrush = new CanvasSolidColorBrush(_canvasDevice, _backgroundColor))
                            {
                                solidColorBrush.Opacity = _backgroundOpacity;
                                double rel = context.InputFrame.RelativeTime.Value.Ticks / (double)TimeSpan.TicksPerMillisecond;

                                //context.OutputFrame.Duration = new TimeSpan( (long)(frameLength * TimeSpan.TicksPerMillisecond));



                                int frameTimeCounter = (int)Math.Round(rel / _frameLength, 0);

                                int[] pitch = new int[_count];
                                int[] yaw   = new int[_count];
                                int[] fov   = new int[_count];

                                for (int i = 0; i < _count; i++)
                                {
                                    try
                                    {
                                        //pitch[i] = this.pitch[ (frameTimeCounter + (int)Math.Round(offset, 0)) * (count) + i];
                                        //fov[i] = this.fov[ (frameTimeCounter + (int)Math.Round(offset, 0)) * (count) + i];
                                        //yaw[i] = this.yaw[ (frameTimeCounter + (int)Math.Round(offset, 0)) * (count) + i];

                                        pitch[i] = this._pitch[(frameTimeCounter + (int)_offset) * (_count) + i];
                                        fov[i]   = this._fov[(frameTimeCounter + (int)_offset) * (_count) + i];
                                        yaw[i]   = this._yaw[(frameTimeCounter + (int)_offset) * (_count) + i];
                                    }
                                    catch (ArgumentOutOfRangeException ex)
                                    {
                                        Debug.WriteLine(ex.Message);
                                        pitch[i] = 0;
                                        fov[i]   = 0;
                                        yaw[i]   = 0;
                                    }
                                }

                                byte[]       tab = Heatmap.GenerateHeatmap(pitch, yaw, fov);
                                CanvasBitmap cb  = CanvasBitmap.CreateFromBytes(_canvasDevice, tab, 64, 64, Windows.Graphics.DirectX.DirectXPixelFormat.B8G8R8A8UIntNormalized, 96, CanvasAlphaMode.Premultiplied);
                                scaleEffect.Source            = cb;
                                scaleEffect.Scale             = new System.Numerics.Vector2((float)_width / 64, (float)_height / 64);
                                scaleEffect.InterpolationMode = CanvasImageInterpolation.Cubic;
                                scaleEffect.BorderMode        = EffectBorderMode.Hard;


                                if (_graysclaleVideoFlag)
                                {
                                    var grayScaleEffect = new GrayscaleEffect
                                    {
                                        BufferPrecision = CanvasBufferPrecision.Precision8UIntNormalized,
                                        CacheOutput     = false,
                                        Source          = inputBitmap
                                    };
                                    ds.DrawImage(grayScaleEffect);
                                }
                                else
                                {
                                    ds.DrawImage(inputBitmap);
                                }

                                ds.DrawImage(scaleEffect, 0, 0, new Windows.Foundation.Rect {
                                    Height = _height, Width = _width
                                }, _heatmapOpacity);



                                if (_generateDots)
                                {
                                    for (int i = 0; i < _count; i++)
                                    {
                                        ds.FillCircle(yaw[i] * _width / 64, pitch[i] * _height / 64, _dotsRadius, _colors[i % 5]);
                                    }
                                }



                                ds.FillRectangle(new Windows.Foundation.Rect {
                                    Height = _height, Width = _width
                                }, solidColorBrush);

                                ds.Flush();
                            }
        }
示例#33
0
        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())));
            }
        }
        private void _canvasControl_Draw(CanvasControl sender, CanvasDrawEventArgs args)
        {
            if (_currentTrack?.ArtworkUrl != null)
            {
                var uri = _currentTrack.ArtworkUrl.ToString();
                uri = uri.Replace("large.jpg", "t500x500.jpg");
                if (!string.IsNullOrWhiteSpace(uri))
                {

                    _scaleEffect = new ScaleEffect();
                    _blurEffect = new GaussianBlurEffect();

                    _image = CanvasBitmap.LoadAsync(sender.Device,
                        new Uri(uri)).GetAwaiter().GetResult();

                    _imageLoaded = true;

                    //sender.Invalidate();
                }
            }
            else
            {_scaleEffect = new ScaleEffect();
                    _blurEffect = new GaussianBlurEffect();

                    _image = CanvasBitmap.LoadAsync(sender.Device,
                        new Uri("ms-appx:///Assets/10SoundBackground.png")).GetAwaiter().GetResult();

                    _imageLoaded = true;
            }
            if (_imageLoaded)
            {
                using (var session = args.DrawingSession)
                {
                    session.Units = CanvasUnits.Pixels;

                    double displayScaling = DisplayInformation.GetForCurrentView().LogicalDpi / 96.0;
                    double pixelWidth;
                    if (sender.ActualWidth > sender.ActualHeight)
                    {
                        pixelWidth = sender.ActualWidth * displayScaling;
                    }
                    else
                    {
                        pixelWidth = sender.ActualHeight * displayScaling;
                    }

                    var scalefactor = pixelWidth / _image.Size.Width;

                    _scaleEffect.Source = _image;
                    _scaleEffect.Scale = new Vector2
                    {
                        X = (float)scalefactor,
                        Y = (float)scalefactor
                    };

                    _blurEffect.Source = _scaleEffect;
                    if(Window.Current.Bounds.Width < 720)
                    {
                        _blurEffect.BlurAmount = 0;
                    }
                    else
                    {
                        _blurEffect.BlurAmount = 100;
                    }
                    
                    session.DrawImage(_blurEffect, 2.0f, 2.0f);

                }
            }
        }
示例#35
0
 internal virtual void drawImage(CanvasBitmap canvasBitmap, int x, int y, int w, int h)
 {
     ScaleEffect scale = new ScaleEffect()
     {
         Source = canvasBitmap,
         Scale = new Vector2()
         {
             X = ((float)w) / canvasBitmap.SizeInPixels.Width,
             Y = ((float)h) / canvasBitmap.SizeInPixels.Height
         }
     };
     if (isMutable())
     {
         graphics.DrawImage(image2Premultiply(scale), x, y);
     }
     else
     {
         graphics.DrawImage(scale, x, y);
     }
 }
示例#36
0
        public void Draw(CanvasAnimatedDrawEventArgs args)
        {
            if (currentImg == null) return;

            if (currentImg.GaussianBlurCache == null)
            {
                currentImg.GaussianBlurCache = new GaussianBlurEffect()
                {
                    Source = currentImg.Bmp,
                    BlurAmount = 1.0f,
                    Optimization = EffectOptimization.Speed
                };
            }

            if (currentImg.Width > MetroSlideshow.WindowWidth)
            {
                currentImg.Scale = (float)(MetroSlideshow.WindowHeight / currentImg.Height);
            }
            else
            {
                currentImg.Scale = (float)(MetroSlideshow.WindowWidth / currentImg.Width);
            }
            if (frame <= 900)
            {
                if (frame == 0)
                {
                    // Set Default values
                    currentImg.Opacity = 0;
                }
                else if (frame < 200)
                {
                }
                zoom += 0.0001f;
            }
            else if (frame < 1000)
            {
                zoom += 0.005f;
            }
            
            var scaleEffect = new ScaleEffect()
            {
                Source = currentImg.GaussianBlurCache,
                Scale = new Vector2()
                {
                    X = currentImg.Scale + zoom,
                    Y = currentImg.Scale + zoom
                },
            };

            scaleEffect.CenterPoint = new Vector2()
            {
                X = 0,
                Y = 0
            };

            if (frame < 200)
            {
                currentImg.Opacity += 0.002f;
            }
            else if (frame > 900)
            {
                currentImg.Opacity -= 0.003f;
            }

            args.DrawingSession.DrawImage(scaleEffect, new Vector2(), new Rect()
            {
                Height = MetroSlideshow.WindowHeight,
                Width = MetroSlideshow.WindowWidth
            }, currentImg.Opacity);

            //args.DrawingSession.DrawText("COLDPLAY", new Vector2()
            //{
            //    X = x,
            //    Y = (float)(MetroSlideshow.WindowHeight / 2)
            //}, col, texts[0].TextForm);

            //args.DrawingSession.DrawText("clocks", new Vector2()
            //{
            //    X = (float)(MetroSlideshow.WindowWidth / 2),
            //    Y = y
            //}, col, texts[0].TextForm);

            //args.DrawingSession.DrawText(frame.ToString(), new Vector2(), col, texts[0].TextForm);
            x = x + 2;
            y++;
            threshold++;
            if (threshold == 1)
            {
                threshold = 0;
                frame++;
            }
            if (frame == 1200)
            {
                // Resetting variables
                if (ImgIndex < Imgs.Count - 1)
                {
                    ImgIndex++;
                }
                else
                {
                    ImgIndex = 0;
                }
                frame = 0;
                zoom = 0;
            }
        }