private static BitmapSource CreateElementScreenshot(UIElement uiElement) { bool measureValid = uiElement.IsMeasureValid; if (!measureValid) { double width = 300; double height = 300; FrameworkElement frElement = uiElement as FrameworkElement; if (frElement != null) { if (!Double.IsNaN(frElement.Width)) width = frElement.Width; if (!Double.IsNaN(frElement.Height)) height = frElement.Height; } Size size = new Size(width, height); uiElement.Measure(size); uiElement.Arrange(new Rect(size)); } RenderTargetBitmap bmp = new RenderTargetBitmap( (int)uiElement.RenderSize.Width, (int)uiElement.RenderSize.Height, 96, 96, PixelFormats.Default); // this is waiting for dispatcher to perform measure, arrange and render passes uiElement.Dispatcher.Invoke(((Action)(() => { })), DispatcherPriority.Background); bmp.Render(uiElement); return bmp; }
/// <summary> /// Arranges the adorner element on the specified adorner panel. /// </summary> public override void Arrange(AdornerPanel panel, UIElement adorner, Size adornedElementSize) { Point p = new Point(0, 0); if (shape is Line) { var s = shape as Line; double x, y; if (alignment == PlacementAlignment.BottomRight) { x = s.X2; y = s.Y2; } else { x = s.X1; y = s.Y1; } p = new Point(x, y); } else if (shape is Polygon) { var pg = shape as Polygon; p = pg.Points[Index]; } else if (shape is Polyline) { var pg = shape as Polyline; p = pg.Points[Index]; } var transform = shape.RenderedGeometry.Transform; p = transform.Transform(p); adorner.Arrange(new Rect(p.X - 3.5, p.Y - 3.5, 7, 7)); }
public static Cursor CreateCursor(UIElement element, int xHotSpot, int yHotSpot) { element.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity)); element.Arrange(new Rect(0, 0, element.DesiredSize.Width, element.DesiredSize.Height)); RenderTargetBitmap rtb = new RenderTargetBitmap((int)element.DesiredSize.Width, (int)element.DesiredSize.Height, 96, 96, PixelFormats.Pbgra32); rtb.Render(element); PngBitmapEncoder encoder = new PngBitmapEncoder(); encoder.Frames.Add(BitmapFrame.Create(rtb)); MemoryStream ms = new MemoryStream(); encoder.Save(ms); System.Drawing.Bitmap bmp = new System.Drawing.Bitmap(ms); ms.Close(); ms.Dispose(); Cursor cur = InternalCreateCursor(bmp, xHotSpot, yHotSpot); bmp.Dispose(); return cur; }
public static ImageSource ToImageSource(UIElement element, System.Windows.Size size) { element.Measure(size); element.Arrange(new Rect(size)); var bmp = new RenderTargetBitmap((int)size.Width, (int)size.Height, 96, 96, PixelFormats.Pbgra32); bmp.Render(element); return bmp; }
public static MemoryStream ToBitmapStream(UIElement uiElement, double width, double height) { var renderTargetBitmap = new RenderTargetBitmap((int)width, (int)height, 96, 96, new PixelFormat()); uiElement.Arrange(new Rect(0, 0, width, height)); renderTargetBitmap.Render(uiElement); var bitmap = new PngBitmapEncoder(); bitmap.Frames.Add(BitmapFrame.Create(renderTargetBitmap)); var bitmapStream = new MemoryStream(); bitmap.Save(bitmapStream); return bitmapStream; }
public static bool SaveElement(UIElement element, Tile tile) { try { var side = (tile == Tile.Small) ? 159 : 336; element.Measure(new Size(side, side)); element.Arrange(new Rect(0, 0, side, side)); var bmp = new WriteableBitmap(side, side); bmp.Render(element, null); bmp.Invalidate(); var name = tile.ToString() + Guid.NewGuid() + ".png"; using (var isf = IsolatedStorageFile.GetUserStoreForApplication()) { if (!isf.DirectoryExists("/CustomLiveTiles")) { isf.CreateDirectory("/CustomLiveTiles"); } using (var myFileStream = isf.CreateFile("shared/shellcontent/" + name)) { // Encode WriteableBitmap object to a PNG stream. bmp.WritePng(myFileStream); } var filesTodelete = from f in isf.GetFileNames("shared/shellcontent/" + tile + "*").AsQueryable() where !f.EndsWith(name) select f; foreach (var file in filesTodelete) { isf.DeleteFile("shared/shellcontent/" + file); } } SaveTilePart("isostore:/Shared/ShellContent/" + name, tile); } catch (Exception) { Thread.Sleep(1000); if (tile == Tile.Small) { SaveTilePart(GetDefaultSmallTile(), tile); } else { SaveTilePart((tile == Tile.Front) ? GetDefaultFrontTile() : GetDefaultBackTile(), tile); } return false; } return true; }
public static BitmapSource GenerateBitmapSource(UIElement element, double renderWidth, double renderHeight, bool performLayout) { if (performLayout) { element.Measure(new Size(renderWidth, renderHeight)); element.Arrange(new Rect(new Size(renderWidth, renderHeight))); } var bmp = new RenderTargetBitmap((int)renderWidth, (int)renderHeight, 96, 96, PixelFormats.Pbgra32); var dv = new DrawingVisual(); using (DrawingContext dc = dv.RenderOpen()) { dc.DrawRectangle(new VisualBrush(element), null, new Rect(0, 0, renderWidth, renderHeight)); } bmp.Render(dv); return bmp; }
private static void RenderControlToBitmap(UIElement control, [NotNull] string path, int scale = 1, double maxWidth = double.PositiveInfinity, double maxheight = double.PositiveInfinity) { var availableSize = new Size(maxWidth, maxheight); control.Measure(availableSize); var desiredSize = control.DesiredSize; control.Arrange(new Rect(desiredSize)); var dpi = scale * 96; var bmp = new RenderTargetBitmap((int)desiredSize.Width * scale, (int)desiredSize.Height * scale, dpi, dpi, PixelFormats.Pbgra32); bmp.Render(control); var encoder = new PngBitmapEncoder(); encoder.Frames.Add(BitmapFrame.Create(bmp)); var dir = Path.GetDirectoryName(path); if (dir == null) throw new InvalidPathException(path); Directory.CreateDirectory(dir); using (Stream stm = File.Create(path)) encoder.Save(stm); }
private async Task ToImage(UIElement element, double width, double height) { element.Measure(new Size(width, height)); element.Arrange(new Rect { Height = height, Width = width }); element.UpdateLayout(); var bitmap = new WriteableBitmap((int)width, (int)height); bitmap.Render(element, null); bitmap.Invalidate(); await SaveTheImage(bitmap, WideTileUrl); }
private async Task ToImage(UIElement element) { element.Measure(new Size(480, 800)); element.Arrange(new Rect{ Height = 800, Width = 480}); element.UpdateLayout(); var bitmap = new WriteableBitmap(480, 800); bitmap.Render(element, null); bitmap.Invalidate(); await SaveTheImage(bitmap); }
/// <summary> /// Tells ContextLayoutManager to finalize possibly async update. /// Used before accessing services off Visual. /// </summary> //[CodeAnalysis("AptcaMethodsShouldOnlyCallAptcaMethods")] //Tracking internal void UpdateLayout() { VerifyAccess(); //make UpdateLayout to be a NOP if called during UpdateLayout. if (_isInUpdateLayout || _measuresOnStack > 0 || _arrangesOnStack > 0 || _isDead) { return; } #if DEBUG_CLR_MEM bool clrTracingEnabled = false; // Start over with the Measure and arrange counters for this layout pass int measureCLRPass = 0; int arrangeCLRPass = 0; if (CLRProfilerControl.ProcessIsUnderCLRProfiler) { clrTracingEnabled = true; if (CLRProfilerControl.CLRLoggingLevel >= CLRProfilerControl.CLRLogState.Performance) { ++_layoutCLRPass; CLRProfilerControl.CLRLogWriteLine("Begin_Layout_{0}", _layoutCLRPass); } } #endif // DEBUG_CLR_MEM bool etwTracingEnabled = false; long perfElementID = 0; const EventTrace.Keyword etwKeywords = EventTrace.Keyword.KeywordLayout | EventTrace.Keyword.KeywordPerf; if (!_isUpdating && EventTrace.IsEnabled(etwKeywords, EventTrace.Level.Info)) { etwTracingEnabled = true; perfElementID = PerfService.GetPerfElementID(this); EventTrace.EventProvider.TraceEvent(EventTrace.Event.WClientLayoutBegin, etwKeywords, EventTrace.Level.Info, perfElementID, EventTrace.LayoutSource.LayoutManager); } int cnt = 0; bool gotException = true; UIElement currentElement = null; try { invalidateTreeIfRecovering(); while (hasDirtiness || _firePostLayoutEvents) { if (++cnt > 153) { //loop detected. Lets go over to background to let input/user to correct the situation. //most frequently, we get such a loop as a result of input detecting a mouse in the "bad spot" //and some event handler oscillating a layout-affecting property depending on hittest result //of the mouse. Going over to background will not break the loopp but will allow user to //move the mouse so that it goes out of the "bad spot". Dispatcher.BeginInvoke(DispatcherPriority.Background, _updateLayoutBackground, this); currentElement = null; gotException = false; if (etwTracingEnabled) { EventTrace.EventProvider.TraceEvent(EventTrace.Event.WClientLayoutAbort, etwKeywords, EventTrace.Level.Info, 0, cnt); } return; } //this flag stops posting update requests to MediaContext - we are already in one //note that _isInUpdateLayout is close but different - _isInUpdateLayout is reset //before firing LayoutUpdated so that event handlers could call UpdateLayout but //still could not cause posting of MediaContext work item. Posting MediaContext workitem //causes infinite loop in MediaContext. _isUpdating = true; _isInUpdateLayout = true; #if DEBUG_CLR_MEM if (clrTracingEnabled && (CLRProfilerControl.CLRLoggingLevel >= CLRProfilerControl.CLRLogState.Verbose)) { ++measureCLRPass; CLRProfilerControl.CLRLogWriteLine("Begin_Measure_{0}_{1}", _layoutCLRPass, measureCLRPass); } #endif // DEBUG_CLR_MEM if (etwTracingEnabled) { EventTrace.EventProvider.TraceEvent(EventTrace.Event.WClientMeasureBegin, etwKeywords, EventTrace.Level.Info, perfElementID); } // Disable processing of the queue during blocking operations to prevent unrelated reentrancy. using (Dispatcher.DisableProcessing()) { //loop for Measure //We limit the number of loops here by time - normally, all layout //calculations should be done by this time, this limit is here for //emergency, "infinite loop" scenarios - yielding in this case will //provide user with ability to continue to interact with the app, even though //it will be sluggish. If we don't yield here, the loop is goign to be a deadly one //and it will be impossible to save results or even close the window. int loopCounter = 0; DateTime loopStartTime = new DateTime(0); while (true) { if (++loopCounter > 153) { loopCounter = 0; //first bunch of iterations is free, then we start count time //this way, we don't call DateTime.Now in most layout updates if (loopStartTime.Ticks == 0) { loopStartTime = DateTime.UtcNow; } else { TimeSpan loopDuration = (DateTime.UtcNow - loopStartTime); if (loopDuration.Milliseconds > 153 * 2) // 153*2 = magic*science { //loop detected. Lets go over to background to let input work. Dispatcher.BeginInvoke(DispatcherPriority.Background, _updateLayoutBackground, this); currentElement = null; gotException = false; if (etwTracingEnabled) { EventTrace.EventProvider.TraceEvent(EventTrace.Event.WClientMeasureAbort, etwKeywords, EventTrace.Level.Info, loopDuration.Milliseconds, loopCounter); } return; } } } currentElement = MeasureQueue.GetTopMost(); if (currentElement == null) { break; //exit if no more Measure candidates } currentElement.Measure(currentElement.PreviousConstraint); //dmitryt, } if (etwTracingEnabled) { EventTrace.EventProvider.TraceEvent(EventTrace.Event.WClientMeasureEnd, etwKeywords, EventTrace.Level.Info, loopCounter); EventTrace.EventProvider.TraceEvent(EventTrace.Event.WClientArrangeBegin, etwKeywords, EventTrace.Level.Info, perfElementID); } #if DEBUG_CLR_MEM if (clrTracingEnabled && (CLRProfilerControl.CLRLoggingLevel >= CLRProfilerControl.CLRLogState.Verbose)) { CLRProfilerControl.CLRLogWriteLine("End_Measure_{0}_{1}", _layoutCLRPass, measureCLRPass); ++arrangeCLRPass; CLRProfilerControl.CLRLogWriteLine("Begin_Arrange_{0}_{1}", _layoutCLRPass, arrangeCLRPass); } #endif // DEBUG_CLR_MEM //loop for Arrange //if Arrange dirtied the tree go clean it again //We limit the number of loops here by time - normally, all layout //calculations should be done by this time, this limit is here for //emergency, "infinite loop" scenarios - yielding in this case will //provide user with ability to continue to interact with the app, even though //it will be sluggish. If we don't yield here, the loop is goign to be a deadly one //and it will be impossible to save results or even close the window. loopCounter = 0; loopStartTime = new DateTime(0); while (MeasureQueue.IsEmpty) { if (++loopCounter > 153) { loopCounter = 0; //first bunch of iterations is free, then we start count time //this way, we don't call DateTime.Now in most layout updates if (loopStartTime.Ticks == 0) { loopStartTime = DateTime.UtcNow; } else { TimeSpan loopDuration = (DateTime.UtcNow - loopStartTime); if (loopDuration.Milliseconds > 153 * 2) // 153*2 = magic*science { //loop detected. Lets go over to background to let input work. Dispatcher.BeginInvoke(DispatcherPriority.Background, _updateLayoutBackground, this); currentElement = null; gotException = false; if (etwTracingEnabled) { EventTrace.EventProvider.TraceEvent(EventTrace.Event.WClientArrangeAbort, etwKeywords, EventTrace.Level.Info, loopDuration.Milliseconds, loopCounter); } return; } } } currentElement = ArrangeQueue.GetTopMost(); if (currentElement == null) { break; //exit if no more Measure candidates } Rect finalRect = getProperArrangeRect(currentElement); currentElement.Arrange(finalRect); //dmitryt, } if (etwTracingEnabled) { EventTrace.EventProvider.TraceEvent(EventTrace.Event.WClientArrangeEnd, etwKeywords, EventTrace.Level.Info, loopCounter); } #if DEBUG_CLR_MEM if (clrTracingEnabled && (CLRProfilerControl.CLRLoggingLevel >= CLRProfilerControl.CLRLogState.Verbose)) { CLRProfilerControl.CLRLogWriteLine("End_Arrange_{0}_{1}", _layoutCLRPass, arrangeCLRPass); } #endif // DEBUG_CLR_MEM //if Arrange dirtied the tree go clean it again //it is not neccesary to check ArrangeQueue sicnce we just exited from Arrange loop if (!MeasureQueue.IsEmpty) { continue; } //let LayoutUpdated handlers to call UpdateLayout //note that it means we can get reentrancy into UpdateLayout past this point, //if any of event handlers call UpdateLayout sync. Need to protect from reentrancy //in the firing methods below. _isInUpdateLayout = false; } fireSizeChangedEvents(); if (hasDirtiness) { continue; } fireLayoutUpdateEvent(); if (hasDirtiness) { continue; } fireAutomationEvents(); if (hasDirtiness) { continue; } fireSizeChangedEvents(); // if nothing is dirty, one last chance for any size changes to announce. } currentElement = null; gotException = false; } finally { _isUpdating = false; _layoutRequestPosted = false; _isInUpdateLayout = false; if (gotException) { if (etwTracingEnabled) { EventTrace.EventProvider.TraceEvent(EventTrace.Event.WClientLayoutException, etwKeywords, EventTrace.Level.Info, PerfService.GetPerfElementID(currentElement)); } //set indicator _gotException = true; _forceLayoutElement = currentElement; //make attempt to request the subsequent layout calc //some exception handler schemas use Idle priorities to //wait until dust settles. Then they correct the issue noted in the exception handler. //We don't want to attempt to re-do the operation on the priority higher then that. Dispatcher.BeginInvoke(DispatcherPriority.ApplicationIdle, _updateLayoutBackground, this); } } MS.Internal.Text.TextInterface.Font.ResetFontFaceCache(); MS.Internal.FontCache.BufferCache.Reset(); if (etwTracingEnabled) { EventTrace.EventProvider.TraceEvent(EventTrace.Event.WClientLayoutEnd, etwKeywords, EventTrace.Level.Info); } #if DEBUG_CLR_MEM if (clrTracingEnabled && (CLRProfilerControl.CLRLoggingLevel >= CLRProfilerControl.CLRLogState.Performance)) { CLRProfilerControl.CLRLogWriteLine("End_Layout_{0}", _layoutCLRPass); } #endif // DEBUG_CLR_MEM }
public static Size ArrangeDecoratorChild (UIElement child, Size constraint, double borderThickness) { if (child != null) { double actualBorderThickness = Utility.GetActualDecoratorBorderThickness (borderThickness, constraint.Width, constraint.Height); child.Arrange (GetArrangeRectToPassToDecoratorChild (constraint, actualBorderThickness)); } return constraint; }
public override void Arrange(AdornerPanel panel, UIElement adorner, Size adornedElementSize) { adorner.Arrange(new Rect(p.X, p.Y, adornedElementSize.Width, adornedElementSize.Height)); }
/// <summary> /// We initiate the layout on the tree rooted at the Visual to which VisualBrush points. /// </summary> private void DoLayout(UIElement element) { Debug.Assert(element != null); DependencyObject parent = VisualTreeHelper.GetParent(element); if (!(element.IsRootElement) && (parent == null || parent is Visual3D)) { // // PropagateResumeLayout sets the LayoutSuspended flag to false if it were true. // UIElement.PropagateResumeLayout(null, element); element.Measure(new Size(Double.PositiveInfinity, Double.PositiveInfinity)); element.Arrange(new Rect(element.DesiredSize)); } }
public static Cursor CreateCursor(UIElement element, int xHotSpot, int yHotSpot,bool isTransparent) { try { element.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity)); element.Arrange(new Rect(0, 0, element.DesiredSize.Width, element.DesiredSize.Height)); RenderTargetBitmap rtb = new RenderTargetBitmap((int)element.DesiredSize.Width, (int)element.DesiredSize.Height, 96, 96, PixelFormats.Pbgra32); rtb.Render(element); PngBitmapEncoder encoder = new PngBitmapEncoder(); encoder.Frames.Add(BitmapFrame.Create(rtb)); MemoryStream ms = new MemoryStream(); encoder.Save(ms); System.Drawing.Bitmap bmp = new System.Drawing.Bitmap(ms); if (isTransparent) { System.Drawing.Color backColor = bmp.GetPixel(1, 1); bmp.MakeTransparent(backColor); } Cursor cur = InternalCreateCursor(bmp, xHotSpot, yHotSpot); ms.Close(); ms.Dispose(); //VictorDEBUG bmp.Dispose(); return cur; } catch { } return null; }
private void ArrangeChild(UIElement child) { if (child.NativeUIElement != null) { SizeF needSize = new SizeF(); if (this.childSizeCache.ContainsKey(child)) { needSize = this.childSizeCache[child]; } else { needSize = child.MeasureOverride(new SizeF(nfloat.PositiveInfinity, nfloat.PositiveInfinity)); this.childSizeCache[child] = needSize; } child.Arrange(new RectangleF((nfloat)Canvas.GetLeft(child), (nfloat)Canvas.GetTop(child), needSize.Width, needSize.Height)); } }
/// <summary> /// Arranges the adorner element on the specified adorner panel. /// </summary> public override void Arrange(AdornerPanel panel, UIElement adorner, Size adornedElementSize) { Size adornerSize = CalculateSize(adorner, adornedElementSize); adorner.Arrange(new Rect(CalculatePosition(adornedElementSize, adornerSize), adornerSize)); }
public override void Arrange(AdornerPanel panel, UIElement adorner, Size adornedElementSize) { adorner.Arrange(new Rect(adornedElementSize)); }
private void ScheduleReArrangeIfNeeded(UIElement child) { bool isScheduled; if (this.isChildRearrangeScheduled.TryGetValue(child, out isScheduled) && isScheduled) { return; } this.isChildRearrangeScheduled[child] = true; this.Dispatcher.BeginInvoke( delegate { try { if (child.measuredFor != null) { var measuredSize = child.MeasureOverride(child.measuredFor.Value); if (child.arrangedSize == measuredSize) { child.Arrange(new RectangleF(child.TranslatePoint, child.arrangedSize)); return; } } this.needsResizeChilds.Add(child); this.InvalidateMeasure(); } finally { this.isChildRearrangeScheduled[child] = false; } }); }
private void ArrangeElement(UIElement element, ref Rect rect) { double x = GraphControl.GetBindPointX(element); double y = GraphControl.GetBindPointY(element); var bindPoint = new Point(x, y); rect.Location = mPointTrans.Translate(bindPoint); element.Arrange(rect); }