Exemplo n.º 1
0
        /// <summary>
        ///     Get cropping areas as BitmapFrame
        /// </summary>
        /// <returns></returns>
        public BitmapFrame GetCroppedBitmapFrame()
        {
            var parent = VisualTreeHelper.GetParent(AdornedElement) as UIElement;
            // 1) get current dpi
            var    pSource = PresentationSource.FromVisual(Application.Current.MainWindow);
            Matrix m       = pSource.CompositionTarget.TransformToDevice;
            double dpiX    = m.M11 * 96;
            double dpiY    = m.M22 * 96;

            // 2) create RenderTargetBitmap
            var elementBitmap = new RenderTargetBitmap(
                (int)AdornedElement.RenderSize.Width,
                (int)AdornedElement.RenderSize.Height,
                dpiX,
                dpiY,
                PixelFormats.Default
                );

            //Important
            AdornedElement.Measure(AdornedElement.RenderSize);
            AdornedElement.Arrange(new Rect(AdornedElement.RenderSize));

            // 3) draw element
            elementBitmap.Render(AdornedElement);

            if (parent != null)
            {
                //Important
                parent.Measure(AdornedElement.RenderSize);
                parent.Arrange(new Rect(AdornedElement.RenderSize));
            }

            var crop = new CroppedBitmap(
                elementBitmap,
                new Int32Rect(
                    (int)_rectangleManager.TopLeft.X,
                    (int)_rectangleManager.TopLeft.Y,
                    (int)_rectangleManager.RectangleWidth,
                    (int)_rectangleManager.RectangleHeight
                    )
                );

            return(BitmapFrame.Create(crop));
        }