Example #1
0
 private static byte[] GetPngImage(FrameworkElement element)
 {
     var size = new Size(double.PositiveInfinity, double.PositiveInfinity);
     element.Measure(size);
     element.Arrange(new Rect(element.DesiredSize));
     var renderTarget =
       new RenderTargetBitmap((int)element.RenderSize.Width,
                              (int)element.RenderSize.Height,
                              96, 96,
                              PixelFormats.Pbgra32);
     var sourceBrush = new VisualBrush(element);
     var drawingVisual = new DrawingVisual();
     using (DrawingContext drawingContext = drawingVisual.RenderOpen())
     {
         drawingContext.DrawRectangle(
             sourceBrush, null, new Rect(
                                    new Point(0, 0),
                                    new Point(element.RenderSize.Width,
                                    element.RenderSize.Height)));
     }
     renderTarget.Render(drawingVisual);
     var pngEncoder = new PngBitmapEncoder();
     pngEncoder.Frames.Add(BitmapFrame.Create(renderTarget));
     using (var outputStream = new MemoryStream())
     {
         pngEncoder.Save(outputStream);
         return outputStream.ToArray();
     }
 }
Example #2
0
		public static void RealizeFrameworkElement(FrameworkElement fe) {
			var size = new Size(double.MaxValue, double.MaxValue);
			if (fe.Width > 0 && fe.Height > 0) size = new Size(fe.Width, fe.Height);
			fe.Measure(size);
			fe.Arrange(new Rect(new Point(), fe.DesiredSize));
			fe.UpdateLayout();
		}
Example #3
0
 public Size UpdateAndMeasure(FrameworkElement element)
 {
     element.LayoutTransform = ChildRenderTransform;
     element.UpdateLayout();
     element.Measure(new Size(BodySize.Width, double.PositiveInfinity));
     return element.DesiredSize;
 }
Example #4
0
        public static Visual Print(Visual v, bool canReturn = false)
        {
            try
            {
                System.Windows.FrameworkElement e = v as System.Windows.FrameworkElement;
                if (e == null)
                {
                    return(null);
                }
                PrintDialog pd = new PrintDialog();

                bool?determiner = true;

                if (!canReturn)
                {
                    determiner = pd.ShowDialog();
                }


                if ((bool)determiner)
                {
                    //store original scale
                    Transform originalScale = e.LayoutTransform;
                    //get selected printer capabilities
                    System.Printing.PrintCapabilities capabilities = pd.PrintQueue.GetPrintCapabilities(pd.PrintTicket);
                    //get scale of the print wrt to screen of WPF visual
                    //double x = capabilities.PageImageableArea.ExtentWidth / e.ActualWidth;
                    //double y = capabilities.PageImageableArea.ExtentHeight / e.ActualHeight;
                    double scale = Math.Min(capabilities.PageImageableArea.ExtentWidth / e.ActualWidth, capabilities.PageImageableArea.ExtentHeight / e.ActualHeight);
                    //Transform the Visual to scale
                    e.LayoutTransform = new ScaleTransform(scale, scale);
                    //  e.LayoutTransform = new ScaleTransform(x, y);
                    //get the size of the printer page
                    System.Windows.Size sz = new System.Windows.Size(capabilities.PageImageableArea.ExtentWidth, capabilities.PageImageableArea.ExtentHeight);
                    //update the layout of the visual to the printer page size.
                    e.Measure(sz);
                    e.Arrange(new System.Windows.Rect(new System.Windows.Point(capabilities.PageImageableArea.OriginWidth, capabilities.PageImageableArea.OriginHeight), sz));
                    //now print the visual to printer to fit on the one page.
                    if (!canReturn)
                    {
                        pd.PrintVisual(v, "My Print");
                        //apply the original transform.
                        e.LayoutTransform = originalScale;
                        MessageBox.Show("Printing SuccessFul", "Operation Successful", MessageBoxButton.OK, MessageBoxImage.Information);
                    }
                }

                if (canReturn)
                {
                    return(v);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }

            return(null);
        }
        private void DoWithElementAtSize(FrameworkElement element, Size size, Action action)
        {
            Transform transform = element.LayoutTransform;
            element.LayoutTransform = null;

            element.Measure(size);
            element.Arrange(new Rect(size));

            action();

            element.LayoutTransform = transform;
        }
        private static void Print(Visual v)
        {
            System.Windows.FrameworkElement e = v as System.Windows.FrameworkElement;
            if (e == null)
            {
                return;
            }

            PrintDialog pd = new PrintDialog();

            if (pd.ShowDialog() == true)
            {
                //store original scale
                Transform originalScale = e.LayoutTransform;
                //get selected printer capabilities

                System.Printing.PrintCapabilities capabilities = pd.PrintQueue.GetPrintCapabilities(pd.PrintTicket);

                //get scale of the print wrt to screen of WPF visual
                if (capabilities.PageImageableArea == null)
                {
                    return;
                }
                double scale = Math.Min(
                    capabilities.PageImageableArea.ExtentWidth / e.ActualWidth,
                    capabilities.PageImageableArea.ExtentHeight / e.ActualHeight);

                //Transform the Visual to scale
                e.LayoutTransform = new ScaleTransform(scale, scale);

                //get the size of the printer page
                System.Windows.Size sz = new System.Windows.Size(
                    capabilities.PageImageableArea.ExtentWidth, capabilities.PageImageableArea.ExtentHeight);

                //update the layout of the visual to the printer page size.
                e.Measure(sz);
                e.Arrange(
                    new System.Windows.Rect(
                        new System.Windows.Point(
                            capabilities.PageImageableArea.OriginWidth, capabilities.PageImageableArea.OriginHeight),
                        sz));

                //now print the visual to printer to fit on the one page.
                pd.PrintVisual(v, "My Print");

                //apply the original transform.
                e.LayoutTransform = originalScale;
            }
        }
		protected virtual void InvalidatePosition(FrameworkElement child)
		{
			if (viewport == null) return;

			var transform = GetTransform(availableSize);

			Size elementSize = GetElementSize(child, AvailableSize, transform);
			child.Measure(elementSize);

			Rect bounds = GetElementScreenBounds(transform, child);
			if (!bounds.IsNaN())
			{
				child.Arrange(bounds);
			}
		}
Example #8
0
        public static ImageSource ToImageSource(FrameworkElement obj)
        {
            Transform transform = obj.LayoutTransform;
            Thickness margin = obj.Margin;
            obj.Margin = new Thickness(0, 0, margin.Right - margin.Left, margin.Bottom - margin.Top);
            Size size = new Size(obj.ActualWidth, obj.ActualHeight);
            obj.Measure(size);
            obj.Arrange(new Rect(size));
            RenderTargetBitmap bmp = new RenderTargetBitmap((int)obj.ActualWidth, (int)obj.ActualHeight, 96, 96, PixelFormats.Pbgra32);

            bmp.Render(obj);
            obj.LayoutTransform = transform;
            obj.Margin = margin;
            return bmp;
        }
        public bool TryAdd(FrameworkElement control)
        {
            control.Measure(new Size(Width, Height));
              Children.Add(control);

              var sizeAfterControlHasBeenAdded = MeasureOverride(new Size(Width, Height));

              // If the new size is larger than the WrapPanel remove the control and return false
              if (sizeAfterControlHasBeenAdded.Width > Width || sizeAfterControlHasBeenAdded.Height > Height)
              {
            Children.Remove(control);
            return false;
              }
              return true;
        }
Example #10
0
        public WpfVisual(FrameworkElement element, int defaultWidth = BadgeCaps.Width, int defaultHeight = BadgeCaps.Height, bool dither = false, bool enableBlend = false)
        {
            Element = element;
            Element.Measure(new Size(defaultWidth, defaultHeight));
            Element.Arrange(new Rect(0, 0, defaultWidth, defaultHeight));

            ClipWidth = (int)Math.Ceiling(Element.ActualWidth);
            ClipHeight = (int)Math.Ceiling(Element.ActualHeight);

            Dither = dither;
            EnableBlend = enableBlend;

            m_cachedIntermediate = new BadgeRenderTarget(ClipWidth, ClipHeight);
            m_renderTarget = new RenderTargetBitmap(ClipWidth, ClipHeight, 96, 96, PixelFormats.Pbgra32);

            Update(0); // To avoid remeasuring on a background thread
            UpdateCachedImage();
        }
Example #11
0
        public static void XAMLToBitmap(FrameworkElement element, string fileName)
        {
            try
            {
                element.RenderTransform = new ScaleTransform(0.1, 0.1);

                element.Measure(new Size((int)element.Width, (int)element.Height));
                element.Arrange(new Rect(new Size((int)element.Width, (int)element.Height)));

                var renderTargetBitmap = new RenderTargetBitmap((int)element.ActualWidth / 10, (int)element.ActualHeight / 10, 96d, 96d, PixelFormats.Pbgra32);
                renderTargetBitmap.Render(element);

                using (FileStream fileStream = new FileStream(fileName, FileMode.Create))
                {
                    var bmpBitmapEncoder = new BmpBitmapEncoder();
                    bmpBitmapEncoder.Frames.Add(BitmapFrame.Create(renderTargetBitmap));
                    bmpBitmapEncoder.Save(fileStream);
                }
            }
            catch { }
        }
        /// <summary>
        /// Creates <seealso cref="WriteableBitmap"/> from a <seealso cref="FrameworkElement"/> to
        /// </summary>
        /// <remarks>This is an extension method provided by <seealso cref="FrameworkElementEx"/></remarks>
        public static WriteableBitmap CreateBitmap(FrameworkElement element, bool isElementInVisualTree = false)
        {
            WriteableBitmap bitmap = null;

            if (!isElementInVisualTree)
            {
                element.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity));
                element.Arrange(new Rect(new Point(0, 0), element.DesiredSize));
            }

            var width  = (int)Math.Ceiling(element.ActualWidth);
            var height = (int)Math.Ceiling(element.ActualHeight);

            width  = width == 0 ? 1 : width;
            height = height == 0 ? 1 : height;

            var rtbmp = new RenderTargetBitmap(width, height, 96, 96, PixelFormats.Default);

            rtbmp.Render(element);
            bitmap = new WriteableBitmap(rtbmp);

            return(bitmap);
        }
		protected override void InvalidatePosition(FrameworkElement child)
		{
			invalidatePositionCalls++;

			if (viewport == null) return;
			if (child.Visibility != Visibility.Visible)
				return;

			var transform = viewport.Transform;

			Size elementSize = GetElementSize(child, AvailableSize, transform);
			child.Measure(elementSize);

			Rect bounds = GetElementScreenBounds(transform, child);
			child.Arrange(bounds);

			var viewportBounds = Viewport2D.GetContentBounds(this);
			if (!viewportBounds.IsEmpty)
				overallViewportBounds = viewportBounds;

			UniteWithBounds(transform, bounds);

			if (!InBatchAdd)
			{
				Viewport2D.SetContentBounds(this, overallViewportBounds);
				ContentBoundsChanged.Raise(this);
			}
		}
Example #14
0
        /// <summary>
        /// Calculates visual size
        /// </summary>
        /// <param name="visual">Visual as FrameworkElement</param>
        /// <returns>Visual size</returns>
        public static Size CalculateVisualSize(FrameworkElement visual)
        {
            Size retVal = new Size(0,0);

            if (visual != null)
            {   
                visual.Measure(new Size(Double.MaxValue, Double.MaxValue));
                retVal = visual.DesiredSize;
            }

            return retVal;
        }
Example #15
0
        /// <summary>
        /// The modify position.
        /// </summary>
        /// <param name="fe">
        /// The fe.
        /// </param>
        private static void ModifyPosition(FrameworkElement fe)
        {
            var fs = new Size(
                fe.ActualWidth + fe.Margin.Left + fe.Margin.Right, fe.ActualHeight + fe.Margin.Top + fe.Margin.Bottom);

            fe.Measure(fs);

            fe.Arrange(new Rect(-fe.Margin.Left, -fe.Margin.Top, fs.Width, fs.Height));
        }
Example #16
0
        /// <summary>
        /// Method for safe printing all on one page
        /// </summary>
        /// <param name="v">Visual to be printed</param>
        /// <param name="page">Page to be printed</param>
        private void Print(Visual v, int page)
        {
            System.Windows.FrameworkElement e = v as System.Windows.FrameworkElement;
            if (e == null)
            {
                return;
            }

            PrintDialog pd = new PrintDialog();

            // mandate specific page
            pd.UserPageRangeEnabled = false;
            pd.PageRange            = new PageRange(page);

            // set to id maker
            try
            {
                pd.PrintQueue = new System.Printing.PrintQueue(new System.Printing.PrintServer(), Properties.Settings.Default.PrinterName);
            }
            catch (Exception ex)
            {
#if DEBUG
                MessageBox.Show("Exception caught during printer choosing.\r\n\r\n" +
                                ex.Message +
                                "\r\nCurrent printer in Properties.Resources: " +
                                Properties.Settings.Default.PrinterName + ".",
                                "Exception",
                                MessageBoxButton.OK,
                                MessageBoxImage.Error);
#else
                MessageBoxResult exRes = MessageBox.Show("Ensure your " +
                                                         Properties.Settings.Default.PrinterName +
                                                         " is plugged in and ready." +
                                                         "\r\n\r\nPrint to another printer?",
                                                         "Error printing.",
                                                         MessageBoxButton.OKCancel,
                                                         MessageBoxImage.Error,
                                                         MessageBoxResult.Cancel);
                switch (exRes)
                {
                case MessageBoxResult.OK:
                    break;

                case MessageBoxResult.Cancel:
                    return;
                }
#endif
            }

            if (pd.ShowDialog().Value)
            {
                //store original scale
                Transform originalScale = e.LayoutTransform;
                //get selected printer capabilities
                System.Printing.PrintCapabilities capabilities = pd.PrintQueue.GetPrintCapabilities(pd.PrintTicket);

                //get scale of the print wrt to screen of WPF visual
                double scale = Math.Min(capabilities.PageImageableArea.ExtentWidth / e.ActualWidth, capabilities.PageImageableArea.ExtentHeight /
                                        e.ActualHeight);

                //Transform the Visual to scale
                e.LayoutTransform = new ScaleTransform(scale, scale);

                //get the size of the printer page
                System.Windows.Size sz = new System.Windows.Size(capabilities.PageImageableArea.ExtentWidth, capabilities.PageImageableArea.ExtentHeight);

                //update the layout of the visual to the printer page size.
                e.Measure(sz);
                e.Arrange(new System.Windows.Rect(new System.Windows.Point(capabilities.PageImageableArea.OriginWidth, capabilities.PageImageableArea.OriginHeight), sz));

                //now print the visual to printer to fit on the one page.
                pd.PrintVisual(v, "My Print");

                //apply the original transform.
                e.LayoutTransform = originalScale;
            }
        }
Example #17
0
 /// <summary>
 /// The modify position back.
 /// </summary>
 /// <param name="fe">
 /// The fe.
 /// </param>
 private static void ModifyPositionBack(FrameworkElement fe)
 {
     fe.Measure(new Size());
 }
Example #18
0
        /// <summary>
        /// This tells a visual to render itself to a wpf bitmap.  From there, you can get the bytes (colors), or run it through a converter
        /// to save as jpg, bmp files.
        /// </summary>
        /// <remarks>
        /// This fixes an issue where the rendered image is blank:
        /// http://blogs.msdn.com/b/jaimer/archive/2009/07/03/rendertargetbitmap-tips.aspx
        /// </remarks>
        public static BitmapSource RenderControl(FrameworkElement visual, int width, int height, bool isInVisualTree)
        {
            if (!isInVisualTree)
            {
                // If the visual isn't part of the visual tree, then it needs to be forced to finish its layout
                visual.Width = width;
                visual.Height = height;
                visual.Measure(new Size(width, height));        //  I thought these two statements would be expensive, but profiling shows it's mostly all on Render
                visual.Arrange(new Rect(0, 0, width, height));
            }

            RenderTargetBitmap retVal = new RenderTargetBitmap(width, height, DPI, DPI, PixelFormats.Pbgra32);

            DrawingVisual dv = new DrawingVisual();
            using (DrawingContext ctx = dv.RenderOpen())
            {
                VisualBrush vb = new VisualBrush(visual);
                ctx.DrawRectangle(vb, null, new Rect(new Point(0, 0), new Point(width, height)));
            }

            retVal.Render(dv);      //  profiling shows this is the biggest hit

            return retVal;
        }
Example #19
0
        partial void InitializeBusyIndicator()
        {
            if (BusyIndicator != null)
            {
                return;
            }

            BusyIndicator = CreateBusyIndicator();
            BusyIndicator.DataContext = _busyIndicatorDataContext;

            _containerPopup = new Popup();
            _containerPopup.VerticalAlignment = VerticalAlignment.Center;
            _containerPopup.HorizontalAlignment = HorizontalAlignment.Center;
            _containerPopup.Child = BusyIndicator;

            _containerPopup.LayoutUpdated += (sender, e) =>
            {
                if (Application.Current == null)
                {
                    return;
                }

                // 1 is the default old behavior but since we set both horizontal and vertical offset, we might
                // be causing a "Layout cycle"
                _skipLayoutUpdateCount++;
                if (_skipLayoutUpdateCount < 2)
                {
                    return;
                }

                _skipLayoutUpdateCount = 0;

                var parent = _parent.Target as FrameworkElement;
                if (parent == null)
                {
                    return;
                }

                try
                {
                    if (parent.ActualHeight == 0.0d && parent.ActualWidth == 0.0d)
                    {
                        Hide();
                        return;
                    }

                    var transform = parent.TransformToVisual(Application.Current.RootVisual);
                    var offset = transform.Transform(new Point(0, 0));
                    double parentTop = offset.Y;
                    double parentLeft = offset.X;

                    // Allow fallback to root (Host.Content)
                    double parentWidth = Application.Current.Host.Content.ActualWidth;
                    double parentHeight = Application.Current.Host.Content.ActualHeight;

                    if (_parent != null)
                    {
                        parentWidth = (parent.ActualWidth > 0) ? parent.ActualWidth : parentWidth;
                        parentHeight = (parent.ActualHeight > 0) ? parent.ActualHeight : parentHeight;
                    }

                    BusyIndicator.Measure(new System.Windows.Size(parentWidth, parentHeight));
                    var busyIndicatorSize = BusyIndicator.DesiredSize;

                    double indicatorWidth = (busyIndicatorSize.Width > 0) ? busyIndicatorSize.Width : DefaultBusyIndicatorWidth;
                    double indicatorHeight = (busyIndicatorSize.Height > 0) ? busyIndicatorSize.Height : DefaultBusyIndicatorHeight;

                    _containerPopup.HorizontalOffset = parentLeft + ((parentWidth / 2) - (indicatorWidth / 2));
                    _containerPopup.VerticalOffset = parentTop + ((parentHeight / 2) - (indicatorHeight / 2));
                }
                catch (Exception)
                {
                    // Ignore
                }
            };

            return;
        }
Example #20
0
 private static void PrepareForExport(FrameworkElement element)
 {
     if (element.ActualWidth == 0 && element.ActualHeight == 0)
     {
         double width = element.Width > 0 ? element.Width : 500;
         double height = element.Height > 0 ? element.Height : 300;
         element.Measure(Size.Empty);
         element.Measure(new Size(width, height));
         element.Arrange(new Rect(0, 0, width, height));
         element.UpdateLayout();
     }
 }
        public RenderTargetBitmap SaveControl(FrameworkElement Target)
        {
            FrameworkElement Parent = Target.Parent as FrameworkElement;
            double ParentWidth, ParentHeight;

            if (Parent == null)
            {
                ParentWidth = 1000;
                ParentHeight = 1000;

                Canvas ParentCanvas = new Canvas();
                ParentCanvas.Children.Add(Target);
                Parent = ParentCanvas;
            }
            else
            {
                ParentWidth = Parent.ActualWidth;
                ParentHeight = Parent.ActualHeight;
            }

            Target.Measure(new Size(ParentWidth, ParentHeight));
            Target.Arrange(new Rect(0, 0, ParentWidth, ParentHeight));

            Target.Measure(new Size(Target.ActualWidth, Target.ActualHeight));
            Target.Arrange(new Rect(0, 0, Target.ActualWidth, Target.ActualHeight));

            Rect Rect = Target.TransformToVisual(Parent).TransformBounds(new Rect(0, 0, Target.ActualWidth, Target.ActualHeight));

            Target.Arrange(new Rect(-Rect.Left, -Rect.Top, Target.ActualWidth, Target.ActualHeight));

            RenderTargetBitmap r = new RenderTargetBitmap((int)Rect.Width, (int)Rect.Height, 96.0, 96.0, PixelFormats.Pbgra32);
            r.Render(Target);

            return r;
        }
        public ImageSource ToImageSource(FrameworkElement obj)
        {
            // Save current canvas transform
            Transform transform = obj.LayoutTransform;

            // fix margin offset as well
            Thickness margin = obj.Margin;
            obj.Margin = new Thickness(0, 0,
                 margin.Right - margin.Left, margin.Bottom - margin.Top);

            // Get the size of canvas
            Size size = new Size(obj.ActualWidth, obj.ActualHeight);

            // force control to Update
            obj.Measure(size);
            obj.Arrange(new Rect(size));

            RenderTargetBitmap bmp = new RenderTargetBitmap(
                (int)obj.ActualWidth, (int)obj.ActualHeight, 96, 96, PixelFormats.Pbgra32);

            bmp.Render(obj);

            // return values as they were before
            obj.LayoutTransform = transform;
            obj.Margin = margin;
            return bmp;
        }
 public static void SetClip(FrameworkElement element)
 {
     element.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity));
     element.Clip = new RectangleGeometry { Rect = new Rect(0, 0, element.ActualWidth, element.ActualHeight) };
 }
Example #24
0
 public static void animateExpand(FrameworkElement elem)
 {
     if (elem.ActualHeight < 20)
     {
         elem.Height = double.NaN; //auto height
         elem.Visibility = Visibility.Visible;
         elem.Measure(new Size(2000,2000));
         double height = (elem.DesiredSize.Height > 0) ? elem.DesiredSize.Height : elem.ActualHeight;
         DoubleAnimation pAnimation = createDoubleAnimation(height, 1000, false);
         elem.Height = 0;
         elem.Visibility = Visibility.Visible;
         pAnimation.FillBehavior = FillBehavior.Stop;
         pAnimation.Completed += delegate(object sender, EventArgs pEvent)
         {
             elem.Height = Double.NaN;
             //elem.BeginAnimation(FrameworkElement., null);
         };
         //pAnimation.Freeze();
         elem.BeginAnimation(FrameworkElement.HeightProperty, pAnimation, HandoffBehavior.SnapshotAndReplace);
     }
 }
Example #25
0
        /// <summary>
        ///     Convert any control to a PngBitmapEncoder
        /// </summary>
        /// <param name="controlToConvert"> The control to convert to an ImageSource </param>
        /// <returns> The returned ImageSource of the controlToConvert </returns>
        /// <see cref="http://www.dreamincode.net/code/snippet4326.htm" />
        public static PngBitmapEncoder GetImageFromControl(FrameworkElement controlToConvert)
        {
            // get size of control
            var sizeOfControl = new System.Windows.Size(controlToConvert.ActualWidth, controlToConvert.ActualHeight);
            // measure and arrange the control
            controlToConvert.Measure(sizeOfControl);
            // arrange the surface
            controlToConvert.Arrange(new Rect(sizeOfControl));

            // craete and render surface and push bitmap to it
            var renderBitmap = new RenderTargetBitmap((Int32)sizeOfControl.Width, (Int32)sizeOfControl.Height, 96d, 96d, PixelFormats.Pbgra32);
            // now render surface to bitmap
            renderBitmap.Render(controlToConvert);
            // encode png data
            var pngEncoder = new PngBitmapEncoder();
            // puch rendered bitmap into it
            pngEncoder.Frames.Add(BitmapFrame.Create(renderBitmap));
            //pngEncoder.Metadata = new BitmapMetadata("png") {
            //                                                    ApplicationName = "Marvelous",
            //                                                    DateTaken = DateTime.Now.ToString(CultureInfo.InvariantCulture),
            //                                                    Subject = "Casual Loop Analysis using Marvel",
            //                                                    Title = "Marvelous screenshot",
            //                                                    Author = new ReadOnlyCollection<string>(new List<string> {
            //                                                                                                                 Properties.Settings.Default.UserName
            //                                                                                                             })
            //                                                };

            // return encoder
            return pngEncoder;
        }
Example #26
0
        public static BitmapSource SaveImageSource(FrameworkElement obj, int width, int height)
        {
            // Save current canvas transform
            obj.LayoutTransform = null;
            obj.Width = width;
            obj.Height = height;
            obj.UpdateLayout();
            obj.UpdateLayout();
            // fix margin offset as well
            Thickness margin = obj.Margin;
            obj.Margin = new Thickness(0, 0,
                 margin.Right - margin.Left, margin.Bottom - margin.Top);

            // Get the size of canvas
            Size size = new Size(width, height);

            // force control to Update
            obj.Measure(size);
            obj.Arrange(new Rect(size));
            RenderTargetBitmap bmp = new RenderTargetBitmap(
                width, height, 96, 96, PixelFormats.Pbgra32);

            bmp.Render(obj);

            //// return values as they were before
            //obj.LayoutTransform = transform;
            //obj.Margin = margin;
            obj = null;
            return bmp;
        }
        /// <summary>
        /// Measures the height of an element
        /// </summary>
        /// <param name="element"></param>
        /// <returns></returns>
        private double MeasureHeight(FrameworkElement element)
        {
            if (element == null)
                throw new ArgumentNullException("element");

            element.Measure(this.PageSize);
            return element.DesiredSize.Height;
        }
Example #28
0
        public void DisplayViewInSplitPanel(string url, NavigationParameters parameter)
        {
            Action operation = () => 
            {
                var uri = new Uri(url, UriKind.Relative);
                _loadedEdgePanel = (FrameworkElement)Application.LoadComponent(uri);

                _loadedEdgePanel.Loaded += (sender, evt) => SplitterPanelLoaded(sender, evt, parameter);
                _splitWindowContent.Children.Clear();
                var contains = _splitWindowContent.Children.Contains(_loadedEdgePanel);
                _splitWindowContent.Children.Add(_loadedEdgePanel);

                // Force the metro window to calculate the size of the user control.
                _loadedEdgePanel.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity));
                _splitWindowContent.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity));
                _splitWindow.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity));

                DisplayEdgePanel();
            };

            if (_isEdgePanelOpen)
            {
                HideEdgePanel(operation);
            }
            else
            {
                operation();
            }
        }
        /// <summary>
        /// Measures the height of an element
        /// </summary>
        /// <param name="element"></param>
        /// <returns></returns>
        private double MeasureHeight(FrameworkElement element)
        {
            if (element == null)
                throw new ArgumentNullException("element");

            double width = this.PageSize.Width - (this.PageMargin.Left + this.PageMargin.Right);
            double height = this.PageSize.Height - (this.PageMargin.Top + this.PageMargin.Bottom);

            element.Measure(new Size(width, height));
            return element.DesiredSize.Height;
        }
Example #30
0
        private static bool TryPlacePopup(Windows.Popup popup, FrameworkElement parent, FrameworkElement placementParent, FrameworkElement placementChild, PopupOrientation orientation)
        {
            var availableWidth = placementParent.ActualWidth;
            var availableHeight = placementParent.ActualHeight;

            SetActualOrientation(popup, orientation);
            placementChild.Measure(new Size(availableWidth, availableHeight));

            var requiredWidth = placementChild.DesiredSize.Width;
            var requiredHeight = placementChild.DesiredSize.Height;
            var placementTarget = GetPlacementTarget(popup) ?? parent;
            var parentTransform = placementTarget.TransformToVisual(parent);
            var popupLocation = parentTransform.Transform(new Point(0, 0));

            switch (orientation.Placement)
            {
                case PopupPlacement.Top:
                    popupLocation.Y -= requiredHeight;
                    break;
                case PopupPlacement.Bottom:
                    popupLocation.Y += placementTarget.ActualHeight;
                    break;
                case PopupPlacement.Left:
                    popupLocation.X -= requiredWidth;
                    break;
                case PopupPlacement.Right:
                    popupLocation.X += placementTarget.ActualWidth;
                    break;
            }

            if (orientation.Placement == PopupPlacement.Top || orientation.Placement == PopupPlacement.Bottom)
            {
                switch (orientation.HorizontalAlignment)
                {
                    case PopupHorizontalAlignment.RightCenter:
                        popupLocation.X += ((placementTarget.ActualWidth / 2) - requiredWidth);
                        break;
                    case PopupHorizontalAlignment.Center:
                        popupLocation.X += ((placementTarget.ActualWidth - requiredWidth) / 2);
                        break;
                    case PopupHorizontalAlignment.LeftCenter:
                        popupLocation.X += (placementTarget.ActualWidth / 2);
                        break;
                    case PopupHorizontalAlignment.Right:
                        popupLocation.X += (placementTarget.ActualWidth - requiredWidth);
                        break;
                }
            }

            if (orientation.Placement == PopupPlacement.Left || orientation.Placement == PopupPlacement.Right)
            {
                switch (orientation.VerticalAlignment)
                {
                    case PopupVerticalAlignment.BottomCenter:
                        popupLocation.Y += ((placementTarget.ActualHeight / 2) - requiredHeight);
                        break;
                    case PopupVerticalAlignment.Center:
                        popupLocation.Y += ((placementTarget.ActualHeight - requiredHeight) / 2);
                        break;
                    case PopupVerticalAlignment.TopCenter:
                        popupLocation.Y += (placementTarget.ActualHeight / 2);
                        break;
                    case PopupVerticalAlignment.Bottom:
                        popupLocation.Y += (placementTarget.ActualHeight - requiredHeight);
                        break;
                }
            }

            var popupLocationRelativeToPlacementParent = popupLocation;

            if (parent != placementParent)
            {
                var placementParentTransform = placementTarget.TransformToVisual(placementParent);
                popupLocationRelativeToPlacementParent = placementParentTransform.Transform(popupLocation);
            }

            if (popupLocationRelativeToPlacementParent.X < 0
                || popupLocationRelativeToPlacementParent.Y < 0
                || (popupLocationRelativeToPlacementParent.X + requiredWidth) > availableWidth
                || (popupLocationRelativeToPlacementParent.Y + requiredHeight) > availableHeight)
            {
                // not enough room
                return false;
            }

            popup.HorizontalOffset = popupLocation.X;
            popup.VerticalOffset = popupLocation.Y;

            return true;
        }
Example #31
0
        private Stream RenderImage(FrameworkElement c)
        {
            c.Measure(new Size(c.Width, Double.IsNaN(c.Height) ? 9999 : c.Height));
            c.Arrange(new Rect(c.DesiredSize));

            RenderTargetBitmap renderBitmap = new RenderTargetBitmap((int)c.ActualWidth,
                                                                     (int)c.ActualHeight, 96, 96, PixelFormats.Pbgra32);

            renderBitmap.Render(c);
            //DrawingVisual visual = new DrawingVisual();
            //using (DrawingContext context = visual.RenderOpen()) {
            //    VisualBrush brush = new VisualBrush(c);
            //    context.DrawRectangle(brush, null, new Rect(c.RenderSize));
            //}

            //visual.Transform = new ScaleTransform(width / c.ActualWidth, height / c.ActualHeight);
            //renderBitmap.Render(visual);

            var stream = new MemoryStream();
            var encoder = new PngBitmapEncoder();
            encoder.Frames.Add(BitmapFrame.Create(renderBitmap));
            encoder.Save(stream);
            return stream;
        }
Example #32
0
 private static Size GetDesiredSize(FrameworkElement cell, Size maxSize)
 {
     double width = cell.Width;
     double height = cell.Height;
     cell.Width = double.NaN;
     cell.Height = double.NaN;
     cell.Measure(maxSize);
     Size desiredSize = cell.DesiredSize;
     cell.Width = width;
     cell.Height = height;
     return desiredSize;
 }
Example #33
-1
        public static void AskToPrint( FrameworkElement ctrl
                                     , string printJobDesc = "Scaled Visual")
        {
            PrintDialog print = new PrintDialog();
            if (print.ShowDialog() != true) return;

            PrintCapabilities capabilities = print.PrintQueue.GetPrintCapabilities(print.PrintTicket);

            double scale = Math.Min(capabilities.PageImageableArea.ExtentWidth / ctrl.ActualWidth,
                                    capabilities.PageImageableArea.ExtentHeight / ctrl.ActualHeight);

            //Transform oldTransform = ctrl.LayoutTransform;

            ctrl.LayoutTransform = new ScaleTransform(scale, scale);

            //Size oldSize = new Size(ctrl.ActualWidth, ctrl.ActualHeight);

            Size sz = new Size(capabilities.PageImageableArea.ExtentWidth, capabilities.PageImageableArea.ExtentHeight);
            ctrl.Measure(sz);
            ((UIElement)ctrl).Arrange(new Rect(new Point(capabilities.PageImageableArea.OriginWidth, capabilities.PageImageableArea.OriginHeight),
                sz));

            ctrl.Focus();

            print.PrintVisual(ctrl, printJobDesc);
            //ctrl.LayoutTransform = oldTransform;

            //ctrl.Measure(oldSize);

            //((UIElement)ctrl).Arrange(new Rect(new Point(0, 0),
            //    oldSize));
        }
Example #34
-1
        public static void Print(FrameworkElement visual)
        {
            PrintDialog dialog = new PrintDialog();
            if (dialog.ShowDialog() == true)
            {

                System.Printing.PrintCapabilities capabilities = dialog.PrintQueue.GetPrintCapabilities(dialog.PrintTicket);
                double scale = Math.Min(capabilities.PageImageableArea.ExtentWidth / visual.ActualWidth, capabilities.PageImageableArea.ExtentHeight / visual.ActualHeight);
                Transform originalTransform = visual.LayoutTransform;
                visual.LayoutTransform = new ScaleTransform(scale, scale);
                Size sz = new Size(capabilities.PageImageableArea.ExtentWidth, capabilities.PageImageableArea.ExtentHeight);
                visual.Measure(sz);
                visual.Arrange(new Rect(new Point(capabilities.PageImageableArea.OriginWidth, capabilities.PageImageableArea.OriginHeight), sz));
                dialog.PrintVisual(visual, "Chart");
                visual.LayoutTransform = originalTransform;
            }
        }