Ejemplo n.º 1
0
 private void ThisUnloaded(object sender, RoutedEventArgs e)
 {
     DisplayInformation.DisplayContentsInvalidated -= DisplayInformation_DisplayContentsInvalidated;
     _canvas?.RemoveFromVisualTree();
     _canvas = null;
     // dispose buffers
     _buffer.Dispose();
     _tmpBuffer.Dispose();
     _background.Dispose();
     foreach (var buffer in _undoBuffer)
     {
         buffer.Value.Dispose();
     }
     foreach (var buffer in _redoBuffer)
     {
         buffer.Value.Dispose();
     }
     foreach (var layer in _layers)
     {
         layer.Image.Dispose();
     }
     _undoBuffer.Clear();
     _redoBuffer.Clear();
     _layers.Clear();
     _buffer     = null;
     _tmpBuffer  = null;
     _background = null;
 }
Ejemplo n.º 2
0
 public void Clear()
 {
     Content?.Clear();
     CacheBitmap?.Dispose();
     CacheEffect?.Dispose();
     CacheBitmap = null;
     CacheEffect = null;
 }
Ejemplo n.º 3
0
 public void Resize(ICanvasResourceCreator resourceCreator, bool force)
 {
     if (needResize || force || renderTarget == null)
     {
         renderTarget?.Dispose();
         renderTarget = new CanvasRenderTarget(resourceCreator, ClipImage.Width.Value < 10 ? 10 : ClipImage.Width.Value, ClipImage.Height.Value < 10 ? 10 : ClipImage.Height.Value, 96);
         needResize   = false;
     }
 }
Ejemplo n.º 4
0
 public void Dispose()
 {
     Debug.Assert(!_disposed);
     _disposed = true;
     _native?.Dispose();
     GC.SuppressFinalize(this);
 }
Ejemplo n.º 5
0
        void DemandCreateBloomRenderTarget(ICanvasAnimatedControl sender)
        {
            float w = (float)sender.Size.Width;
            float h = (float)sender.Size.Height;

            // Early-out if we already have a rendertarget of the correct size.
            // Compare sizes as pixels rather than dips to avoid rounding artifacts.
            if (bloomRenderTarget != null &&
                bloomRenderTarget.SizeInPixels.Width == sender.ConvertDipsToPixels(w) &&
                bloomRenderTarget.SizeInPixels.Height == sender.ConvertDipsToPixels(h))
            {
                return;
            }

            // Destroy the old rendertarget.
            if (bloomRenderTarget != null)
            {
                bloomRenderTarget.Dispose();
            }

            // Create the new rendertarget.
            bloomRenderTarget = new CanvasRenderTarget(sender, w, h);

            // Configure the bloom effect to use this new rendertarget.
            extractBrightAreas.Source = bloomRenderTarget;
            bloomResult.Background    = bloomRenderTarget;
        }
Ejemplo n.º 6
0
        void DemandCreateBloomRenderTarget(ICanvasAnimatedControl sender)
        {
            // Early-out if we already have a rendertarget of the correct size.
            // This compares against a stored copy of sender.Size, rather than reading back bloomRenderTarget.Size,
            // because the actual rendertarget size will be rounded to an integer number of pixels,
            // thus may not be identical to the size that was passed in when constructing the rendertarget.
            var senderSize = sender.Size;

            if (bloomRenderTarget != null &&
                bloomRenderTargetSize == senderSize &&
                bloomRenderTarget.Dpi == sender.Dpi)
            {
                return;
            }

            // Destroy the old rendertarget.
            if (bloomRenderTarget != null)
            {
                bloomRenderTarget.Dispose();
            }

            // Create the new rendertarget.
            bloomRenderTarget     = new CanvasRenderTarget(sender, senderSize);
            bloomRenderTargetSize = senderSize;

            // Configure the bloom effect to use this new rendertarget.
            extractBrightAreas.Source = bloomRenderTarget;
            bloomResult.Background    = bloomRenderTarget;
        }
Ejemplo n.º 7
0
        public void MultithreadedSaveToFile()
        {
            //
            // This test can create a deadlock if that SaveAsync code holds on to the
            // ID2D1Multithread resource lock longer than necessary.
            //
            // A previous implementation waited until destruction of the IAsyncAction before calling Leave().
            // In managed code this can happen on an arbitrary thread and so could result in deadlock situations
            // where other worker threads were waiting for a Leave on the original thread that never arrived.
            //

            var task = Task.Run(async() =>
            {
                var device = new CanvasDevice();
                var rt     = new CanvasRenderTarget(device, 16, 16, 96);

                var filename = Path.Combine(ApplicationData.Current.TemporaryFolder.Path, "testfile.jpg");

                await rt.SaveAsync(filename);

                rt.Dispose();
            });

            task.Wait();
        }
Ejemplo n.º 8
0
        public void MultithreadedSaveToFile()
        {
            //
            // This test can create a deadlock if the SaveAsync code holds on to the
            // ID2D1Multithread resource lock longer than necessary.
            //
            // A previous implementation waited until destruction of the IAsyncAction before calling Leave().  
            // In managed code this can happen on an arbitrary thread and so could result in deadlock situations
            // where other worker threads were waiting for a Leave on the original thread that never arrived.
            //

            using (new DisableDebugLayer()) // 6184116 causes the debug layer to fail when CanvasBitmap::SaveAsync is called
            {
                var task = Task.Run(async () =>
                {
                    var device = new CanvasDevice();
                    var rt = new CanvasRenderTarget(device, 16, 16, 96);

                    var filename = Path.Combine(ApplicationData.Current.TemporaryFolder.Path, "testfile.jpg");

                    await rt.SaveAsync(filename);

                    rt.Dispose();
                });

                task.Wait();
            }
        }
Ejemplo n.º 9
0
        private void ResetFramePool(SizeInt32 size, bool recreateDevice)
        {
            do
            {
                try
                {
                    if (recreateDevice)
                    {
                        _canvasDevice = new CanvasDevice();
                        foreach (var clip in ClipImages.Values)
                        {
                            clip.Resize(_canvasDevice, true);
                        }
                    }

                    _framePool.Recreate(
                        _canvasDevice,
                        DirectXPixelFormat.B8G8R8A8UIntNormalized,
                        2,
                        size);
                    renderTarget.Dispose();
                    renderTarget = new CanvasRenderTarget(_canvasDevice, size.Width, size.Height, 96);
                }
                // This is the device-lost convention for Win2D.
                catch (Exception e) when(_canvasDevice.IsDeviceLost(e.HResult))
                {
                    _canvasDevice  = null;
                    recreateDevice = true;
                }
            } while (_canvasDevice == null);
        }
Ejemplo n.º 10
0
        // Can only be run on the UI thread
        void createDestinationTarget()
        {
            // Don't run if not on the UI thread
            if (!Container.Dispatcher.HasThreadAccess)
            {
                return;
            }
            // Don't run if no video is loaded
            if (Player.PlaybackSession.NaturalVideoWidth == 0)
            {
                return;
            }
            double containerRatio = Container.ActualWidth / Container.ActualHeight, videoRatio = (double)Player.PlaybackSession.NaturalVideoWidth / Player.PlaybackSession.NaturalVideoHeight;

            double dW, dH;

            if (containerRatio < videoRatio)
            {
                dH = Container.ActualHeight;
                dW = dH * videoRatio;
            }
            else
            {
                dW = Container.ActualWidth;
                dH = dW / videoRatio;
            }
            // Multiply the width and height of the UI container by the device's scale factor
            var display = DisplayInformation.GetForCurrentView();
            int width = (int)MyMath.Round(dW * display.RawPixelsPerViewPixel), height = (int)MyMath.Round(dH * display.RawPixelsPerViewPixel);

            if (width < 1 || height < 1)
            {
                return;
            }

            lock (ResourceLock)
            {
                if (destinationTarget == null || destinationTarget.Description.Width != width || destinationTarget.Description.Height != height)
                {
                    destinationTarget?.Dispose();
                    destinationTarget = new CanvasRenderTarget(CanvasDevice, width, height, 96);
                    if (DrawingSurface == null)
                    {
                        DrawingSurface = CompositionDevice.CreateDrawingSurface2(new SizeInt32()
                        {
                            Width = width, Height = height
                        }, DirectXPixelFormat.B8G8R8A8UIntNormalized, DirectXAlphaMode.Premultiplied);
                        SurfaceBrush.Surface = DrawingSurface;
                    }
                    else
                    {
                        DrawingSurface.Resize(new SizeInt32()
                        {
                            Width = width, Height = height
                        });
                    }
                }
            }
        }
Ejemplo n.º 11
0
        public async Task SaveAsync(StorageFile file, bool measuresOnly)
        {
            if (file == null || measureBitmap == null)
            {
                return;
            }

            Debug.WriteLine(file.ContentType + "   " + file.FileType);
            var fileType = file.ContentType?.Trim().ToLower();
            CanvasBitmapFileFormat fileFormat = CanvasBitmapFileFormat.Png;

            switch (fileType)
            {
            case "image/jpeg":
                fileFormat = CanvasBitmapFileFormat.Jpeg;
                break;

            case "image/bmp":
                fileFormat = CanvasBitmapFileFormat.Bmp;
                break;

            case "image/gif":
                fileFormat = CanvasBitmapFileFormat.Gif;
                break;

            case "image/png":
            default:
                break;
            }

            var device = CanvasDevice.GetSharedDevice();
            var size   = measureBitmap.Size;
            var target = new CanvasRenderTarget(device, (float)size.Width, (float)size.Height,
                                                measureBitmap.Dpi, DirectXPixelFormat.B8G8R8A8UIntNormalized,
                                                CanvasAlphaMode.Premultiplied);

            using (var g = target.CreateDrawingSession())
            {
                g.Clear(fileFormat == CanvasBitmapFileFormat.Png ? Colors.Transparent : Colors.White);
                if (!measuresOnly)
                {
                    g.DrawImage(measureBitmap);
                    g.Antialiasing     = CanvasAntialiasing.Antialiased;
                    g.TextAntialiasing = CanvasTextAntialiasing.Auto;
                }
                foreach (var item in measureObjects)
                {
                    item.Draw(g, false);
                }
            }
            var stream = await file.OpenAsync(FileAccessMode.ReadWrite);

            await target.SaveAsync(stream, fileFormat);

            stream.Dispose();
            target.Dispose();
        }
Ejemplo n.º 12
0
        public void RecoverAfterDeviceLost()
        {
            if (cachedImage != null)
            {
                cachedImage.Dispose();
                cachedImage = null;
            }

            isCacheValid = false;
        }
Ejemplo n.º 13
0
        public void UndoRegionEdit()
        {
            if (previousRegionMask != null)
            {
                regionMask.SetPixelBytes(previousRegionMask);
                currentRegionMask  = previousRegionMask;
                previousRegionMask = null;
            }
            else
            {
                regionMask.Dispose();
                regionMask        = null;
                currentRegionMask = null;
            }

            cachedRegionMask.Reset();

            CanUndo = false;
        }
        public void ResetBitmapResources()
        {
            if (canvasBitmap != null)
            {
                canvasBitmap.Dispose();
                canvasBitmap = null;
            }

            if (canvasRenderTarget != null)
            {
                canvasRenderTarget.Dispose();
                canvasRenderTarget = null;
            }

            if (canvasRenderTargetPreview != null)
            {
                canvasRenderTargetPreview.Dispose();
                canvasRenderTargetPreview = null;
            }
            
        }
 protected virtual void Dispose(Boolean disposing)
 {
     if (!disposed)
     {
         if (disposing == true && coreUnitBuffer != null)
         {
             coreUnitBuffer.Dispose();
             coreUnitBuffer = null;
         }
         disposed = true;
     }
 }
Ejemplo n.º 16
0
 protected virtual void Dispose(Boolean disposing)
 {
     if (!disposed)
     {
         if (disposing == true && _crt != null)
         {
             _crt.Dispose();
             _crt = null;
         }
         disposed = true;
     }
 }
Ejemplo n.º 17
0
        //Dispose variables and clear memory
        void DisposeVariables()
        {
            try
            {
                Debug.WriteLine("Setting the last background task run date.");
                vApplicationSettings["BgStatusLastRunDate"] = DateTimeNow.ToString(vCultureInfoEng);

                Debug.WriteLine("Disposing variables and clearing memory.");
                if (Win2DCanvasDevice != null)
                {
                    Win2DCanvasDevice.Dispose();
                }
                if (Win2DCanvasRenderTarget != null)
                {
                    Win2DCanvasRenderTarget.Dispose();
                }
                if (Win2DCanvasBitmap != null)
                {
                    Win2DCanvasBitmap.Dispose();
                }
                if (Win2DCanvasImageBrush != null)
                {
                    Win2DCanvasImageBrush.Dispose();
                }
                if (Win2DCanvasTextFormatTitle != null)
                {
                    Win2DCanvasTextFormatTitle.Dispose();
                }
                if (Win2DCanvasTextFormatBody != null)
                {
                    Win2DCanvasTextFormatBody.Dispose();
                }
                if (Win2DCanvasTextFormatSub != null)
                {
                    Win2DCanvasTextFormatSub.Dispose();
                }
                if (Win2DCanvasTextFormatTextLeft != null)
                {
                    Win2DCanvasTextFormatTextLeft.Dispose();
                }
                if (Win2DCanvasTextFormatTextRight != null)
                {
                    Win2DCanvasTextFormatTextRight.Dispose();
                }
                if (Win2DCanvasTextFormatTextCenter != null)
                {
                    Win2DCanvasTextFormatTextCenter.Dispose();
                }
            }
            catch { }
        }
Ejemplo n.º 18
0
 public void StopCapture()
 {
     foreach (var clip in ClipImages.Values)
     {
         clip.Stop();
     }
     renderTarget?.Dispose();
     _session?.Dispose();
     _framePool?.Dispose();
     _item        = null;
     _session     = null;
     _framePool   = null;
     renderTarget = null;
 }
Ejemplo n.º 19
0
        protected override void OnNavigatedFrom(NavigationEventArgs e)
        {
            _radialConfiguration.IsMenuSuppressed = false;

            _radialController.RotationChanged      -= RadialController_RotationChanged;
            _radialController.ScreenContactStarted -= RadialController_ScreenContactStarted;
            _radialController.ScreenContactEnded   -= RadialController_ScreenContactEnded;
            _radialController.ButtonPressed        -= RadialController_ButtonPressed;
            _radialController.ButtonReleased       -= RadialController_ButtonReleased;

            _effect.Dispose();
            _canvasBitmap.Dispose();
            _canvasRenderTarget.Dispose();
        }
Ejemplo n.º 20
0
        /// <summary>
        /// Saves the entire bitmap to the specified stream
        /// with the specified file format and quality level.
        /// </summary>
        /// <param name="renderTarget"> The render target.</param>
        /// <param name="fileChoices"> The file choices. </param>
        /// <param name="suggestedFileName"> The suggested name of file. </param>
        /// <param name="fileFormat"> The file format. </param>
        /// <param name="quality"> The file quality. </param>
        /// <returns> Saved successful? </returns>
        public static async Task <bool> SaveCanvasBitmapFile(CanvasRenderTarget renderTarget, string fileChoices = ".Jpeg", string suggestedFileName = "Untitled", CanvasBitmapFileFormat fileFormat = CanvasBitmapFileFormat.Jpeg, float quality = 1.0f)
        {
            //FileSavePicker
            FileSavePicker savePicker = new FileSavePicker
            {
                SuggestedStartLocation = PickerLocationId.Desktop,
                SuggestedFileName      = suggestedFileName,
            };

            savePicker.FileTypeChoices.Add("DB", new[] { fileChoices });


            //PickSaveFileAsync
            StorageFile file = await savePicker.PickSaveFileAsync();

            if (file == null)
            {
                return(false);
            }

            try
            {
                using (IRandomAccessStream accessStream = await file.OpenAsync(FileAccessMode.ReadWrite))
                {
                    await renderTarget.SaveAsync(accessStream, fileFormat, quality);
                }

                renderTarget.Dispose();
                return(true);
            }
            catch (Exception)
            {
                renderTarget.Dispose();
                return(false);
            }
        }
Ejemplo n.º 21
0
        public void MultithreadedSaveToStream()
        {
            // This is the stream version of the above test

            var task = Task.Run(async() =>
            {
                var device = new CanvasDevice();
                var rt     = new CanvasRenderTarget(device, 16, 16, 96);

                var stream = new MemoryStream();
                await rt.SaveAsync(stream.AsRandomAccessStream(), CanvasBitmapFileFormat.Bmp);

                rt.Dispose();
            });

            task.Wait();
        }
Ejemplo n.º 22
0
        public void MultithreadedSaveToStream()
        {
            // This is the stream version of the above test

            var task = Task.Run(async () =>
            {
                var device = new CanvasDevice();
                var rt = new CanvasRenderTarget(device, 16, 16, 96);

                var stream = new MemoryStream();
                await rt.SaveAsync(stream.AsRandomAccessStream(), CanvasBitmapFileFormat.Bmp);

                rt.Dispose();
            });

            task.Wait();
        }
Ejemplo n.º 23
0
        public void MultithreadedSaveToStream()
        {
            // This is the stream version of the above test

            using (new DisableDebugLayer()) // 6184116 causes the debug layer to fail when CanvasBitmap::SaveAsync is called
            {
                var task = Task.Run(async () =>
                {
                    var device = new CanvasDevice();
                    var rt = new CanvasRenderTarget(device, 16, 16, 96);

                    var stream = new MemoryStream();
                    await rt.SaveAsync(stream.AsRandomAccessStream(), CanvasBitmapFileFormat.Bmp);

                    rt.Dispose();
                });

                task.Wait();
            }
        }
Ejemplo n.º 24
0
        public void MultithreadedSaveToStream()
        {
            // This is the stream version of the above test

            using (new DisableDebugLayer()) // 6184116 causes the debug layer to fail when CanvasBitmap::SaveAsync is called
            {
                var task = Task.Run(async() =>
                {
                    var device = new CanvasDevice();
                    var rt     = new CanvasRenderTarget(device, 16, 16, 96);

                    var stream = new MemoryStream();
                    await rt.SaveAsync(stream.AsRandomAccessStream(), CanvasBitmapFileFormat.Bmp);

                    rt.Dispose();
                });

                task.Wait();
            }
        }
Ejemplo n.º 25
0
        public static async Task <StorageFile> DrawStrokesAsync(StorageFile file, IReadOnlyList <SmoothPathBuilder> strokes, Rect rectangle, BitmapRotation rotation, BitmapFlip flip)
        {
            var device = CanvasDevice.GetSharedDevice();
            var bitmap = await CanvasBitmap.LoadAsync(device, file.Path);

            var canvas1 = new CanvasRenderTarget(device, (float)bitmap.Size.Width, (float)bitmap.Size.Height, bitmap.Dpi);
            var canvas2 = new CanvasRenderTarget(device, (float)bitmap.Size.Width, (float)bitmap.Size.Height, bitmap.Dpi);

            var size       = canvas1.Size.ToVector2();
            var canvasSize = canvas1.Size.ToVector2();

            var scaleX = 1 / (float)rectangle.Width;
            var scaleY = 1 / (float)rectangle.Height;

            var offsetX = (float)rectangle.X * scaleX;
            var offsetY = (float)rectangle.Y * scaleY;

            if (rotation is BitmapRotation.Clockwise270Degrees or BitmapRotation.Clockwise90Degrees)
            {
                size = new Vector2(size.Y, size.X);

                scaleX = scaleY;
                scaleY = 1 * 1 / (float)rectangle.Width;
            }

            using (var session = canvas1.CreateDrawingSession())
            {
                switch (rotation)
                {
                case BitmapRotation.Clockwise90Degrees:
                    var transform1 = Matrix3x2.CreateRotation(MathFEx.ToRadians(90));
                    transform1.Translation = new Vector2(size.Y, 0);
                    session.Transform      = transform1;
                    break;

                case BitmapRotation.Clockwise180Degrees:
                    var transform2 = Matrix3x2.CreateRotation(MathFEx.ToRadians(180));
                    transform2.Translation = new Vector2(size.X, size.Y);
                    session.Transform      = transform2;
                    break;

                case BitmapRotation.Clockwise270Degrees:
                    var transform3 = Matrix3x2.CreateRotation(MathFEx.ToRadians(270));
                    transform3.Translation = new Vector2(0, size.X);
                    session.Transform      = transform3;
                    break;
                }

                switch (flip)
                {
                case BitmapFlip.Horizontal:
                    switch (rotation)
                    {
                    case BitmapRotation.Clockwise90Degrees:
                    case BitmapRotation.Clockwise270Degrees:
                        session.Transform = Matrix3x2.Multiply(session.Transform, Matrix3x2.CreateScale(1, -1, canvasSize / 2));
                        break;

                    default:
                        session.Transform = Matrix3x2.Multiply(session.Transform, Matrix3x2.CreateScale(-1, 1, canvasSize / 2));
                        break;
                    }
                    break;

                case BitmapFlip.Vertical:
                    switch (rotation)
                    {
                    case BitmapRotation.None:
                    case BitmapRotation.Clockwise180Degrees:
                        session.Transform = Matrix3x2.Multiply(session.Transform, Matrix3x2.CreateScale(1, -1, canvasSize / 2));
                        break;

                    default:
                        session.Transform = Matrix3x2.Multiply(session.Transform, Matrix3x2.CreateScale(-1, 1, canvasSize / 2));
                        break;
                    }
                    break;
                }

                session.Transform = Matrix3x2.Multiply(session.Transform, Matrix3x2.CreateScale(scaleX, scaleY));
                session.Transform = Matrix3x2.Multiply(session.Transform, Matrix3x2.CreateTranslation(-(offsetX * size.X), -(offsetY * size.Y)));

                foreach (var builder in strokes)
                {
                    PencilCanvas.DrawPath(session, builder, size);
                }
            }

            using (var session = canvas2.CreateDrawingSession())
            {
                session.DrawImage(bitmap);
                session.DrawImage(canvas1);
            }

            bitmap.Dispose();

            using (var stream = await file.OpenAsync(FileAccessMode.ReadWrite))
            {
                await canvas2.SaveAsync(stream, CanvasBitmapFileFormat.Jpeg /*, 0.77f*/);
            }

            canvas2.Dispose();
            canvas1.Dispose();

            return(file);
        }
Ejemplo n.º 26
0
        public void updateRepresentation()
        {
            if (represent != null)
            {
                represent.Dispose();
            }

            CreateBoundBox();

            try
            {
                if (boundbox.Height > 0 && boundbox.Width > 0)
                {
                    represent = new CanvasRenderTarget(device, (int)this.boundbox.Width, (int)this.boundbox.Height, 96);

                    using (CanvasDrawingSession g2d = represent.CreateDrawingSession())
                    {
                        g2d.Clear(Colors.Transparent);

                        g2d.Antialiasing = CanvasAntialiasing.Antialiased;

                        Color bordercolor = Colors.Black;
                        int   linesize    = 2;


                        CalcPoint        second = new CalcPoint();
                        CalcPoint        arrowleft;
                        CalcPoint        arrowright;
                        CalcPoint        direction;
                        List <CalcPoint> pointslist;

                        int xoffset = -(int)(boundbox.X);
                        int yoffset = -(int)(boundbox.Y);

                        pointslist = this.nodes;

                        direction = new CalcPoint(this.PointDirection());

                        /*for (int i = 0; i < pointslist.Count - 1; i++)
                         * {
                         *  second = pointslist.ElementAt(i + 1);
                         *  g2d.DrawLine(pointslist[i].X, second.X, pointslist[i].Y, second.Y, bordercolor, linesize);
                         *
                         * }*/
                        second = pointslist.Last();

                        core.DrawBezier(g2d, pointslist, xoffset, yoffset, bordercolor, linesize);

                        arrowleft  = new CalcPoint(second.X + xoffset, second.Y + yoffset);
                        arrowright = new CalcPoint(second.X + xoffset, second.Y + yoffset);

                        if (direction.X != 0)
                        {
                            arrowleft  = new CalcPoint(second.X + xoffset - 10 * direction.X, second.Y + yoffset - 10);
                            arrowright = new CalcPoint(second.X + xoffset - 10 * direction.X, second.Y + yoffset + 10);
                        }
                        if (direction.Y != 0)
                        {
                            arrowleft  = new CalcPoint(second.X + xoffset - 10, second.Y + yoffset - 10 * direction.Y);
                            arrowright = new CalcPoint(second.X + xoffset + 10, second.Y + yoffset - 10 * direction.Y);
                        }

                        //g2d.DrawLine(new Vector2(second), new Vector2(arrowleft), bordercolor, linesize);
                        core.DrawLine(g2d, second.X + xoffset, second.Y + yoffset, arrowleft.X, arrowleft.Y, bordercolor, linesize);
                        core.DrawLine(g2d, second.X + xoffset, second.Y + yoffset, arrowright.X, arrowright.Y, bordercolor, linesize);
                    }
                }
            }
            catch (Exception e)
            {
            }
        }
Ejemplo n.º 27
0
 public void MaskDispose()
 {
     MaskVirtual.Dispose();
     MaskAnimated.Dispose();
 }
Ejemplo n.º 28
0
 public void TargeDispose()
 {
     Targe.Dispose();
 }
Ejemplo n.º 29
0
        private Task CreateExportTask(CancellationToken cancellationToken)
        {
            return(new Task(() =>
            {
                var provider = this.ExportProvider;
                var mediaEncodingProfile = MediaEncodingProfile.CreateMp4(this.ExportVideoEncodingQuality);
                if (provider?.ExportPartConfigs == null ||
                    this.DestinationFolder == null ||
                    provider.ExportPartConfigs.Count < 1 ||
                    string.IsNullOrEmpty(this.FileName) ||
                    Math.Abs(provider.ExportSize.Width) < 1 ||
                    Math.Abs(provider.ExportSize.Height) < 1 ||
                    mediaEncodingProfile?.Video == null)
                {
                    UpdateExportStatus(false);
                    return;
                }

                var exportSize = provider.ExportSize;
                mediaEncodingProfile.Video.Width = (uint)exportSize.Width;
                mediaEncodingProfile.Video.Height = (uint)exportSize.Height;
                mediaEncodingProfile.Video.FrameRate.Numerator = this.ExportFrameRate;
                var cacheFolder = GetCacheFolder().GetAwaiter().GetResult();
                var device = CanvasDevice.GetSharedDevice();
                var mediafileList = new List <StorageFile>();
                var defaultBackgroud =
                    new CanvasRenderTarget(device, (float)exportSize.Width, (float)exportSize.Height, 96f);
                using (var session = defaultBackgroud.CreateDrawingSession())
                {
                    session.Clear(Colors.White);
                }

                var scale = exportSize.Width / provider.ExportArea.Width;
                var transform = Matrix3x2.CreateScale((float)scale);
                var offsetPoint =
                    Vector2.Transform(new Point(-provider.ExportArea.X, -provider.ExportArea.Y).ToVector2(), transform);
                transform.Translation = offsetPoint;
                var framePosition = new Rect(new Point(), exportSize);
                var timeGap = TimeSpan.FromSeconds(1) / provider.FrameRate;
                foreach (var videoPartConfig in provider.ExportPartConfigs)
                {
                    var composition = new MediaComposition();
                    var layerTmp = new MediaOverlayLayer();
                    var tmpFrameImgs = new List <CanvasBitmap>();
                    if (videoPartConfig.BackgroundVideoClips?.Count > 0)
                    {
                        if (videoPartConfig.Delay.TotalSeconds > 0)
                        {
                            var blankClip = MediaClip.CreateFromColor(Colors.White, videoPartConfig.Delay);
                            composition.Clips.Add(blankClip);
                        }

                        foreach (var videoClip in videoPartConfig.BackgroundVideoClips)
                        {
                            composition.Clips.Add(videoClip);
                        }
                        if (composition.Duration < videoPartConfig.Duration)
                        {
                            var blankClip = MediaClip.CreateFromColor(Colors.White,
                                                                      videoPartConfig.Duration - composition.Duration);
                            composition.Clips.Add(blankClip);
                        }
                    }

                    else
                    {
                        composition.Clips.Add(MediaClip.CreateFromSurface(defaultBackgroud, videoPartConfig.Duration));
                    }

                    if (videoPartConfig.BackgroundAudioTracks?.Count > 0)
                    {
                        foreach (var track in videoPartConfig.BackgroundAudioTracks)
                        {
                            track.Delay -= videoPartConfig.Start;
                            composition.BackgroundAudioTracks.Add(track);
                        }
                    }

                    for (var currentPosition = videoPartConfig.Start;
                         currentPosition < videoPartConfig.Start + videoPartConfig.Duration;
                         currentPosition += timeGap)
                    {
                        if (Canceled)
                        {
                            return;
                        }

                        var progress = (int)(currentPosition / provider.Duration * 100 * 0.5);
                        UpdateProgress(progress);

                        var frame = new CanvasRenderTarget(device, (float)exportSize.Width, (float)exportSize.Height,
                                                           96f);
                        using (var session = frame.CreateDrawingSession())
                        {
                            session.Clear(Colors.Transparent);
                            session.Transform = transform;
                            provider.DrawFrame(session, currentPosition);
                        }

                        tmpFrameImgs.Add(frame);
                        var clip = MediaClip.CreateFromSurface(frame, timeGap);
                        var tmpLayer = new MediaOverlay(clip)
                        {
                            Position = framePosition,
                            Opacity = 1f,
                            Delay = currentPosition - videoPartConfig.Start
                        };
                        layerTmp.Overlays.Add(tmpLayer);
                    }

                    composition.OverlayLayers.Add(layerTmp);
                    var mediaPartFile = cacheFolder.CreateFileAsync(
                        $"part_{mediafileList.Count}.mp4", CreationCollisionOption.ReplaceExisting).GetAwaiter()
                                        .GetResult();
                    composition.RenderToFileAsync(mediaPartFile, MediaTrimmingPreference.Fast,
                                                  mediaEncodingProfile).GetAwaiter().GetResult();
                    mediafileList.Add(mediaPartFile);

                    foreach (var item in tmpFrameImgs)
                    {
                        item.Dispose();
                    }

                    tmpFrameImgs.Clear();
                }

                defaultBackgroud?.Dispose();
                var mediaComposition = new MediaComposition();

                #region connect video

                foreach (var mediaPartFile in mediafileList)
                {
                    if (Canceled)
                    {
                        return;
                    }
                    var mediaPartClip = MediaClip.CreateFromFileAsync(mediaPartFile).GetAwaiter().GetResult();
                    mediaComposition.Clips.Add(mediaPartClip);
                }

                #endregion

                #region add global BackgroundAudioTrack

                if (provider.GlobalBackgroundAudioTracks != null)
                {
                    foreach (var bgm in provider.GlobalBackgroundAudioTracks)
                    {
                        mediaComposition.BackgroundAudioTracks.Add(bgm);
                    }
                }

                #endregion

                #region add watermark

                var watermarkLayer = provider.CreateWatermarkLayer();
                if (watermarkLayer != null)
                {
                    mediaComposition.OverlayLayers.Add(watermarkLayer);
                }

                #endregion


                var exportFile = this.DestinationFolder.CreateFileAsync($"{this.FileName}.mp4", CreationCollisionOption.ReplaceExisting)
                                 .GetAwaiter().GetResult();
                if (Canceled)
                {
                    return;
                }
                var saveOperation = mediaComposition.RenderToFileAsync(exportFile, MediaTrimmingPreference.Fast,
                                                                       mediaEncodingProfile);
                saveOperation.Progress = (info, progress) =>
                {
                    UpdateProgress((int)(50 + progress * 0.5));
                    if (Canceled)
                    {
                        saveOperation.Cancel();
                    }
                };

                saveOperation.Completed = (info, status) =>
                {
                    if (!Canceled)
                    {
                        var results = info.GetResults();
                        if (results != TranscodeFailureReason.None || status != AsyncStatus.Completed)
                        {
                            UpdateExportStatus(false);
                        }
                        else
                        {
                            UpdateExportStatus(true);
                        }
                    }

                    ClearCacheAsync();
                };
            }, cancellationToken));
        }
Ejemplo n.º 30
0
        public void updateRepresentation()
        {
            if (represent != null)
            {
                represent.Dispose();
            }

            try {
                if (height > 0 && width > 0)
                {
                    CanvasDevice device = CanvasDevice.GetSharedDevice();
                    represent = new CanvasRenderTarget(device, this.width, this.height, 96);

                    using (CanvasDrawingSession g2d = represent.CreateDrawingSession())
                    {
                        g2d.Clear(Colors.Transparent);

                        g2d.Antialiasing = CanvasAntialiasing.Antialiased;

                        Color bordercolor = Colors.Black;
                        Color fillcolor   = NodeColor;
                        //int linesize = 5;

                        if (hovered)
                        {
                            fillcolor = Colors.LightGray;
                        }
                        if (selected)
                        {
                            fillcolor = Colors.Green;
                        }

                        style.DrawStyle(g2d, NodeDrawingStyle, 3, 3, width - 6, height - 6, fillcolor, bordercolor, (int)(borderOffset * scale));

                        if (!scaled)
                        {
                            g2d.DrawText(text, (int)(width - textSize.Width) / 2, (int)(height - textSize.Height) / 2, TextColor, NodeTextStyle);
                        }
                        else
                        {
                            g2d.DrawText(text, (int)(width - textSize.Width) / 2, (int)(height - textSize.Height) / 2, TextColor, NodeTextStyle);
                        }

                        repupdated = true;
                    }

                    UpdatePosition();
                    transformrectpicture = new CanvasRenderTarget(device, (float)transformRec.Width, (float)transformRec.Height, 96);
                    using (CanvasDrawingSession g2d = transformrectpicture.CreateDrawingSession())
                    {
                        g2d.DrawRectangle(new Rect(0, 0, transformRec.Width, transformRec.Height), Colors.Black, 2f);

                        /*g2d.DrawRectangle(new Rect(transformBorder, transformBorder, this.width, this.height), Colors.Black, 2f);
                         *
                         * g2d.DrawRectangle(new Rect(0,0,transformBorder, transformBorder), Colors.Black, 2f);
                         * g2d.DrawRectangle(new Rect(0, transformRec.Height- transformBorder, transformBorder, transformBorder), Colors.Black, 2f);
                         * g2d.DrawRectangle(new Rect(transformRec.Width - transformBorder, transformRec.Height - transformBorder, transformBorder, transformBorder), Colors.Black, 2f);
                         * g2d.DrawRectangle(new Rect(transformRec.Width - transformBorder, 0, transformBorder, transformBorder), Colors.Black, 2f);*/
                        g2d.DrawLine(transformBorder, 0, transformBorder, (float)transformRec.Height, Colors.Black, 2f);
                        g2d.DrawLine(0, transformBorder, (float)transformRec.Width, transformBorder, Colors.Black, 2f);
                        g2d.DrawLine(0, (float)transformRec.Height - transformBorder, (float)transformRec.Width, (float)transformRec.Height - transformBorder, Colors.Black, 2f);
                        g2d.DrawLine((float)transformRec.Width - transformBorder, 0, (float)transformRec.Width - transformBorder, (float)transformRec.Height, Colors.Black, 2f);
                    }

                    /*for (int x = 0; x < this.connections.Count; x++)
                     * {
                     *  connections[x].updateRepresentation();
                     * }*/
                }
            }
            catch (Exception e)
            {
            }
        }