public override void Init(TagHelperContext context) { base.Init(context); FormGroupContext = context.GetFormGroupContext(); FormContext = context.GetFormContext(); Size = Size ?? FormContext?.ControlSize; }
public Request(string url, string browser, Size viewportResolution) { Initialize(); _viewportResolution = viewportResolution; Url = url; Browser = browser; }
public TileBuilder(bool missingTilesOnly, bool buildCollectionTiles, string outputFolder, Size? commonSize) { _missingTilesOnly = missingTilesOnly; _buildCollectionTiles = buildCollectionTiles; _outputFolder = outputFolder; _commonSize = commonSize; }
protected override void OnMouseUp(MouseEventArgs e) { mouseGrabOffset = null; base.OnMouseUp(e); if (closeRequested) Close(); }
public override void Init(TagHelperContext context) { base.Init(context); FormContext = context.GetFormContext(); FormGroupContext = context.GetFormGroupContext(); InputGroupContext = context.GetInputGroupContext(); IsInLabel = context.HasLabelContext(); Size = Size ?? FormContext?.ControlSize; if (FormGroupContext != null) FormGroupContext.HasLabel = FormGroupContext.HasLabel || !string.IsNullOrEmpty(Label); }
private void AnimatedImage_SizeChanged(object sender, SizeChangedEventArgs e) { _size = e.NewSize; if (!_hasCreatedProvider) { CreateIfReady(); } else { UpdateRendererSize(); } }
public frmSearch(ISearchConnection searchConnection) { InitializeComponent(); Utils.Gfx.SetFormIcon(this); this._expandedMinSize = this.MinimumSize; this._expandedMaxSize = new Size(0, 0); this._collapsedMinSize = new Size(this.Width - this.ClientRectangle.Width + 2 * this.tcPages.Left + this.tcPages.Width, this.MinimumSize.Height); this._collapsedMaxSize = new Size(this._collapsedMinSize.Value.Width, int.MaxValue); this._searchConnection = searchConnection; this.Status = Statuses.Collapsed; this.cbxTidy_Where.Items.Clear(); this.cbxTidy_Where.Items.Add(PLACE_SOURCE); this.cbxTidy_Where.Items.Add(PLACE_TRANSLATED); this.cbxTidy_Where.SelectedIndex = 1; }
protected override void OnMouseDown(MouseEventArgs e) { if (e.Button == System.Windows.Forms.MouseButtons.Left) if (this.Cursor == Cursors.Hand) mouseGrabOffset = new Size(e.Location); else if (this.Cursor == Cursors.SizeWE && e.X <= 5) ResizingLeft = true; else if (this.Cursor == Cursors.SizeWE && e.X >= this.Width - 5) ResizingWidth = true; else if (this.Cursor == Cursors.SizeNS && e.Y <= 5) ResizingTop = true; else if (this.Cursor == Cursors.SizeNS && e.Y >= this.Height - 5) ResizingHeight = true; base.OnMouseDown(e); }
private void OnScreenCaputred(object sender, ScreenShot2Lib.ScreenCaputredEventArgs e) { //set last size lastSize = new Size(e.Bmp.Width, e.Bmp.Height); Show(); //test var bmp = e.Bmp; var win = new Window {SizeToContent = SizeToContent.WidthAndHeight, ResizeMode= ResizeMode.NoResize}; var canvas = new Canvas {Width = bmp.Width, Height = bmp.Height, Background = new ImageBrush(bmp)}; win.Content = canvas; win.Show(); }
private void StaticImage_SizeChanged(object sender, SizeChangedEventArgs e) { _size = e.NewSize; if (e.NewSize != e.PreviousSize) { if (_isLoading) { _isLoading = false; _cancel.Cancel(); _cancel = null; } ForceLoad().ContinueWith(task => { throw task.Exception; }, TaskContinuationOptions.ExecuteSynchronously | TaskContinuationOptions.OnlyOnFaulted); } }
private void ChangeSizeByBrowser(Size browserSize) { if (!this.settings.AutomaticallyResize) return; // サイズ計算のためにいったんリミット外す this.MinWidth = .0; this.MinHeight = .0; if (this.previousBrowserSize != null) { if (this.previousDock == Dock.Top || this.previousDock == Dock.Bottom) { var diffW = this.previousBrowserSize.Value.Width - browserSize.Width; if (Math.Abs(diffW) > 0.00001) this.Width -= diffW; } else if (this.previousDock == Dock.Left || this.previousDock == Dock.Right) { var diffH = this.previousBrowserSize.Value.Height - browserSize.Height; if (Math.Abs(diffH) > 0.00001) this.Height -= diffH; } } else { if (this.previousDock == Dock.Top || this.previousDock == Dock.Bottom) { this.Height += browserSize.Height; } else if (this.previousDock == Dock.Left || this.previousDock == Dock.Right) { this.Width += browserSize.Width; } } this.MinWidth = browserSize.Width + this.BorderThickness.Left + this.BorderThickness.Right; this.MinHeight = browserSize.Height + this.toolbarArea.ActualHeight + this.captionBar.ActualHeight + this.statusBar.ActualHeight; this.previousBrowserSize = browserSize; }
void TemplateTextEditorForm_FormClosed(object sender, FormClosedEventArgs e) { LastSize = Size; LastLocation = Location; }
/// <summary> /// Tries to find an existing texture, or create a new one if not found. /// </summary> /// <param name="memoryManager">GPU memory manager where the texture is mapped</param> /// <param name="flags">The texture search flags, defines texture comparison rules</param> /// <param name="info">Texture information of the texture to be found or created</param> /// <param name="layerSize">Size in bytes of a single texture layer</param> /// <param name="sizeHint">A hint indicating the minimum used size for the texture</param> /// <param name="range">Optional ranges of physical memory where the texture data is located</param> /// <returns>The texture</returns> public Texture FindOrCreateTexture( MemoryManager memoryManager, TextureSearchFlags flags, TextureInfo info, int layerSize = 0, Size?sizeHint = null, MultiRange?range = null) { bool isSamplerTexture = (flags & TextureSearchFlags.ForSampler) != 0; TextureScaleMode scaleMode = IsUpscaleCompatible(info, (flags & TextureSearchFlags.WithUpscale) != 0); ulong address; if (range != null) { address = range.Value.GetSubRange(0).Address; } else { address = memoryManager.Translate(info.GpuAddress); if (address == MemoryManager.PteUnmapped) { return(null); } } int sameAddressOverlapsCount; lock (_textures) { // Try to find a perfect texture match, with the same address and parameters. sameAddressOverlapsCount = _textures.FindOverlaps(address, ref _textureOverlaps); } Texture texture = null; TextureMatchQuality bestQuality = TextureMatchQuality.NoMatch; for (int index = 0; index < sameAddressOverlapsCount; index++) { Texture overlap = _textureOverlaps[index]; TextureMatchQuality matchQuality = overlap.IsExactMatch(info, flags); if (matchQuality != TextureMatchQuality.NoMatch) { // If the parameters match, we need to make sure the texture is mapped to the same memory regions. if (range != null) { // If a range of memory was supplied, just check if the ranges match. if (!overlap.Range.Equals(range.Value)) { continue; } } else { // If no range was supplied, we can check if the GPU virtual address match. If they do, // we know the textures are located at the same memory region. // If they don't, it may still be mapped to the same physical region, so we // do a more expensive check to tell if they are mapped into the same physical regions. // If the GPU VA for the texture has ever been unmapped, then the range must be checked regardless. if ((overlap.Info.GpuAddress != info.GpuAddress || overlap.ChangedMapping) && !memoryManager.CompareRange(overlap.Range, info.GpuAddress)) { continue; } } } if (matchQuality == TextureMatchQuality.Perfect) { texture = overlap; break; } else if (matchQuality > bestQuality) { texture = overlap; bestQuality = matchQuality; } } if (texture != null) { ChangeSizeIfNeeded(info, texture, isSamplerTexture, sizeHint); texture.SynchronizeMemory(); return(texture); } else if (flags.HasFlag(TextureSearchFlags.NoCreate)) { return(null); } // Calculate texture sizes, used to find all overlapping textures. SizeInfo sizeInfo = info.CalculateSizeInfo(layerSize); ulong size = (ulong)sizeInfo.TotalSize; bool partiallyMapped = false; if (range == null) { range = memoryManager.GetPhysicalRegions(info.GpuAddress, size); for (int i = 0; i < range.Value.Count; i++) { if (range.Value.GetSubRange(i).Address == MemoryManager.PteUnmapped) { partiallyMapped = true; break; } } } // Find view compatible matches. int overlapsCount; lock (_textures) { overlapsCount = _textures.FindOverlaps(range.Value, ref _textureOverlaps); } if (_overlapInfo.Length != _textureOverlaps.Length) { Array.Resize(ref _overlapInfo, _textureOverlaps.Length); } // =============== Find Texture View of Existing Texture =============== int fullyCompatible = 0; // Evaluate compatibility of overlaps, add temporary references for (int index = 0; index < overlapsCount; index++) { Texture overlap = _textureOverlaps[index]; TextureViewCompatibility overlapCompatibility = overlap.IsViewCompatible(info, range.Value, sizeInfo.LayerSize, _context.Capabilities, out int firstLayer, out int firstLevel); if (overlapCompatibility == TextureViewCompatibility.Full) { if (overlap.IsView) { overlapCompatibility = TextureViewCompatibility.CopyOnly; } else { fullyCompatible++; } } _overlapInfo[index] = new OverlapInfo(overlapCompatibility, firstLayer, firstLevel); overlap.IncrementReferenceCount(); } // Search through the overlaps to find a compatible view and establish any copy dependencies. for (int index = 0; index < overlapsCount; index++) { Texture overlap = _textureOverlaps[index]; OverlapInfo oInfo = _overlapInfo[index]; if (oInfo.Compatibility == TextureViewCompatibility.Full) { TextureInfo adjInfo = AdjustSizes(overlap, info, oInfo.FirstLevel); if (!isSamplerTexture) { info = adjInfo; } texture = overlap.CreateView(adjInfo, sizeInfo, range.Value, oInfo.FirstLayer, oInfo.FirstLevel); ChangeSizeIfNeeded(info, texture, isSamplerTexture, sizeHint); texture.SynchronizeMemory(); break; } else if (oInfo.Compatibility == TextureViewCompatibility.CopyOnly && fullyCompatible == 0) { // Only copy compatible. If there's another choice for a FULLY compatible texture, choose that instead. texture = new Texture(_context, _physicalMemory, info, sizeInfo, range.Value, scaleMode); texture.InitializeGroup(true, true, new List <TextureIncompatibleOverlap>()); texture.InitializeData(false, false); overlap.SynchronizeMemory(); overlap.CreateCopyDependency(texture, oInfo.FirstLayer, oInfo.FirstLevel, true); break; } } if (texture != null) { // This texture could be a view of multiple parent textures with different storages, even if it is a view. // When a texture is created, make sure all possible dependencies to other textures are created as copies. // (even if it could be fulfilled without a copy) for (int index = 0; index < overlapsCount; index++) { Texture overlap = _textureOverlaps[index]; OverlapInfo oInfo = _overlapInfo[index]; if (oInfo.Compatibility <= TextureViewCompatibility.LayoutIncompatible) { if (!overlap.IsView && texture.DataOverlaps(overlap, oInfo.Compatibility)) { texture.Group.RegisterIncompatibleOverlap(new TextureIncompatibleOverlap(overlap.Group, oInfo.Compatibility), true); } } else if (overlap.Group != texture.Group) { overlap.SynchronizeMemory(); overlap.CreateCopyDependency(texture, oInfo.FirstLayer, oInfo.FirstLevel, true); } } texture.SynchronizeMemory(); } // =============== Create a New Texture =============== // No match, create a new texture. if (texture == null) { texture = new Texture(_context, _physicalMemory, info, sizeInfo, range.Value, scaleMode); // Step 1: Find textures that are view compatible with the new texture. // Any textures that are incompatible will contain garbage data, so they should be removed where possible. int viewCompatible = 0; fullyCompatible = 0; bool setData = isSamplerTexture || overlapsCount == 0 || flags.HasFlag(TextureSearchFlags.ForCopy); bool hasLayerViews = false; bool hasMipViews = false; var incompatibleOverlaps = new List <TextureIncompatibleOverlap>(); for (int index = 0; index < overlapsCount; index++) { Texture overlap = _textureOverlaps[index]; bool overlapInCache = overlap.CacheNode != null; TextureViewCompatibility compatibility = texture.IsViewCompatible(overlap.Info, overlap.Range, overlap.LayerSize, _context.Capabilities, out int firstLayer, out int firstLevel); if (overlap.IsView && compatibility == TextureViewCompatibility.Full) { compatibility = TextureViewCompatibility.CopyOnly; } if (compatibility > TextureViewCompatibility.LayoutIncompatible) { _overlapInfo[viewCompatible] = new OverlapInfo(compatibility, firstLayer, firstLevel); _textureOverlaps[index] = _textureOverlaps[viewCompatible]; _textureOverlaps[viewCompatible] = overlap; if (compatibility == TextureViewCompatibility.Full) { if (viewCompatible != fullyCompatible) { // Swap overlaps so that the fully compatible views have priority. _overlapInfo[viewCompatible] = _overlapInfo[fullyCompatible]; _textureOverlaps[viewCompatible] = _textureOverlaps[fullyCompatible]; _overlapInfo[fullyCompatible] = new OverlapInfo(compatibility, firstLayer, firstLevel); _textureOverlaps[fullyCompatible] = overlap; } fullyCompatible++; } viewCompatible++; hasLayerViews |= overlap.Info.GetSlices() < texture.Info.GetSlices(); hasMipViews |= overlap.Info.Levels < texture.Info.Levels; } else { bool dataOverlaps = texture.DataOverlaps(overlap, compatibility); if (!overlap.IsView && dataOverlaps && !incompatibleOverlaps.Exists(incompatible => incompatible.Group == overlap.Group)) { incompatibleOverlaps.Add(new TextureIncompatibleOverlap(overlap.Group, compatibility)); } bool removeOverlap; bool modified = overlap.CheckModified(false); if (overlapInCache || !setData) { if (!dataOverlaps) { // Allow textures to overlap if their data does not actually overlap. // This typically happens when mip level subranges of a layered texture are used. (each texture fills the gaps of the others) continue; } // The overlap texture is going to contain garbage data after we draw, or is generally incompatible. // The texture group will obtain copy dependencies for any subresources that are compatible between the two textures, // but sometimes its data must be flushed regardless. // If the texture was modified since its last use, then that data is probably meant to go into this texture. // If the data has been modified by the CPU, then it also shouldn't be flushed. bool flush = overlapInCache && !modified && overlap.AlwaysFlushOnOverlap; setData |= modified || flush; if (overlapInCache) { _cache.Remove(overlap, flush); } removeOverlap = modified; } else { // If an incompatible overlapping texture has been modified, then it's data is likely destined for this texture, // and the overlapped texture will contain garbage. In this case, it should be removed to save memory. removeOverlap = modified; } if (removeOverlap && overlap.Info.Target != Target.TextureBuffer) { overlap.RemoveFromPools(false); } } } texture.InitializeGroup(hasLayerViews, hasMipViews, incompatibleOverlaps); // We need to synchronize before copying the old view data to the texture, // otherwise the copied data would be overwritten by a future synchronization. texture.InitializeData(false, setData); texture.Group.InitializeOverlaps(); for (int index = 0; index < viewCompatible; index++) { Texture overlap = _textureOverlaps[index]; OverlapInfo oInfo = _overlapInfo[index]; if (overlap.Group == texture.Group) { // If the texture group is equal, then this texture (or its parent) is already a view. continue; } TextureInfo overlapInfo = AdjustSizes(texture, overlap.Info, oInfo.FirstLevel); if (texture.ScaleFactor != overlap.ScaleFactor) { // A bit tricky, our new texture may need to contain an existing texture that is upscaled, but isn't itself. // In that case, we prefer the higher scale only if our format is render-target-like, otherwise we scale the view down before copy. texture.PropagateScale(overlap); } if (oInfo.Compatibility != TextureViewCompatibility.Full) { // Copy only compatibility, or target texture is already a view. overlap.SynchronizeMemory(); texture.CreateCopyDependency(overlap, oInfo.FirstLayer, oInfo.FirstLevel, false); } else { TextureCreateInfo createInfo = GetCreateInfo(overlapInfo, _context.Capabilities, overlap.ScaleFactor); ITexture newView = texture.HostTexture.CreateView(createInfo, oInfo.FirstLayer, oInfo.FirstLevel); overlap.SynchronizeMemory(); overlap.HostTexture.CopyTo(newView, 0, 0); overlap.ReplaceView(texture, overlapInfo, newView, oInfo.FirstLayer, oInfo.FirstLevel); } } texture.SynchronizeMemory(); } // Sampler textures are managed by the texture pool, all other textures // are managed by the auto delete cache. if (!isSamplerTexture) { _cache.Add(texture); } lock (_textures) { _textures.Add(texture); } if (partiallyMapped) { lock (_partiallyMappedTextures) { _partiallyMappedTextures.Add(texture); } } ShrinkOverlapsBufferIfNeeded(); for (int i = 0; i < overlapsCount; i++) { _textureOverlaps[i].DecrementReferenceCount(); } return(texture); }
public IAsyncResult BeginGetScreenshot(Rectangle region, TimeSpan timeout, AsyncCallback callback = null, Size?resize = null, ImageFormat format = ImageFormat.Bitmap) { Func <Rectangle, TimeSpan, Size?, ImageFormat, Screenshot> getScreenshot = GetScreenshot; return(getScreenshot.BeginInvoke(region, timeout, resize, format, callback, getScreenshot)); }
private static (FFMpegArguments, Action <FFMpegArgumentOptions> outputOptions) BuildSnapshotArguments(IMediaAnalysis source, Size?size = null, TimeSpan?captureTime = null) { captureTime ??= TimeSpan.FromSeconds(source.Duration.TotalSeconds / 3); size = PrepareSnapshotSize(source, size); return(FFMpegArguments .FromFileInput(source, options => options .Seek(captureTime)), options => options .WithVideoCodec(VideoCodec.Png) .WithFrameOutputCount(1) .Resize(size)); }
private void DrawAim() { if (aimsize == null) { using (var targetbmp = new Bitmap(getfile.GetFile("target.png"))) { aimsize = targetbmp.Size; } } float aimwidth = aimsize.Value.Width; float aimheight = aimsize.Value.Height; Draw2dBitmapFile("target.png", Width / 2 - aimwidth / 2, Height / 2 - aimheight / 2, aimwidth, aimheight); }
/// <summary> /// Invalidates the measurement of the control and queues a new layout pass. /// </summary> public void InvalidateMeasure() { var parent = this.GetVisualParent<ILayoutable>(); if (IsMeasureValid) { _layoutLog.Verbose("Invalidated measure"); } IsMeasureValid = false; IsArrangeValid = false; _previousMeasure = null; _previousArrange = null; if (parent != null && IsResizable(parent)) { parent.InvalidateMeasure(); } else { var root = GetLayoutRoot(); root?.Item1.LayoutManager?.InvalidateMeasure(this, root.Item2); } }
/// <summary> /// Measure string in bitmap /// </summary> /// <param name="text">Text</param> /// <param name="font">Font</param> /// <param name="textformat">String format</param> /// <param name="measurementbox">If given, maximum size of text box</param> /// <returns></returns> public static SizeF MeasureStringInBitmap(string text, Font font, StringFormat textformat, Size?measurementbox = null) { using (Bitmap t = new Bitmap(1, 1)) { using (Graphics g = Graphics.FromImage(t)) { if (measurementbox == null) { measurementbox = new Size(20000, 20000); } g.TextRenderingHint = System.Drawing.Text.TextRenderingHint.ClearTypeGridFit; var ret = g.MeasureString(text, font, measurementbox.Value, textformat); // System.Diagnostics.Debug.WriteLine($"Measure '{text}' in font {font.ToString()} size {ret}"); return(ret); } } }
public virtual void AdjustFixedChildrenPanelSizes(Size?parentSize = null) { var visibleChildren = GetVisibleChildren(); if (visibleChildren.Count == 0) { return; } var layoutChildrenModels = visibleChildren.OfType <ILayoutControl>() .Select(child => child.Model) .OfType <ILayoutPositionableElementWithActualSize>() .ToList(); var splitterChildren = visibleChildren.OfType <LayoutGridResizerControl>().ToList(); List <ILayoutPositionableElementWithActualSize> fixedPanels; List <ILayoutPositionableElementWithActualSize> relativePanels; // Get current available size of panel. var availableSize = parentSize ?? new Size(ActualWidth, ActualHeight); // Calculate minimum required size and current size of children. var minimumSize = new Size(0, 0); var currentSize = new Size(0, 0); var preferredMinimumSize = new Size(0, 0); if (Orientation == Orientation.Vertical) { fixedPanels = layoutChildrenModels.Where(child => child.DockHeight.IsAbsolute).ToList(); relativePanels = layoutChildrenModels.Where(child => !child.DockHeight.IsAbsolute).ToList(); minimumSize.Width += layoutChildrenModels.Max(child => child.CalculatedDockMinWidth()); minimumSize.Height += layoutChildrenModels.Sum(child => child.CalculatedDockMinHeight()); minimumSize.Height += splitterChildren.Sum(child => child.ActualHeight); currentSize.Width += layoutChildrenModels.Max(child => child.ActualWidth); currentSize.Height += layoutChildrenModels.Sum(child => child.ActualHeight); currentSize.Height += splitterChildren.Sum(child => child.ActualHeight); preferredMinimumSize.Width += layoutChildrenModels.Max(child => child.CalculatedDockMinWidth()); preferredMinimumSize.Height += minimumSize.Height + fixedPanels.Sum(child => child.FixedDockHeight) - fixedPanels.Sum(child => child.CalculatedDockMinHeight()); } else { fixedPanels = layoutChildrenModels.Where(child => child.DockWidth.IsAbsolute).ToList(); relativePanels = layoutChildrenModels.Where(child => !child.DockWidth.IsAbsolute).ToList(); minimumSize.Width += layoutChildrenModels.Sum(child => child.CalculatedDockMinWidth()); minimumSize.Height += layoutChildrenModels.Max(child => child.CalculatedDockMinHeight()); minimumSize.Width += splitterChildren.Sum(child => child.ActualWidth); currentSize.Width += layoutChildrenModels.Sum(child => child.ActualWidth); currentSize.Height += layoutChildrenModels.Max(child => child.ActualHeight); currentSize.Width += splitterChildren.Sum(child => child.ActualWidth); preferredMinimumSize.Height += layoutChildrenModels.Max(child => child.CalculatedDockMinHeight()); preferredMinimumSize.Width += minimumSize.Width + fixedPanels.Sum(child => child.FixedDockWidth) - fixedPanels.Sum(child => child.CalculatedDockMinWidth()); } // Apply corrected sizes for fixed panels. if (Orientation == Orientation.Vertical) { var delta = availableSize.Height - currentSize.Height; var relativeDelta = relativePanels.Sum(child => child.ActualHeight - child.CalculatedDockMinHeight()); delta += relativeDelta; foreach (var fixedChild in fixedPanels) { if (minimumSize.Height >= availableSize.Height) { fixedChild.ResizableAbsoluteDockHeight = fixedChild.CalculatedDockMinHeight(); } else if (preferredMinimumSize.Height <= availableSize.Height) { fixedChild.ResizableAbsoluteDockHeight = fixedChild.FixedDockHeight; } else if (relativePanels.All(child => Math.Abs(child.ActualHeight - child.CalculatedDockMinHeight()) <= 1)) { double panelFraction; var indexOfChild = fixedPanels.IndexOf(fixedChild); if (delta < 0) { var availableHeightLeft = fixedPanels.Where(child => fixedPanels.IndexOf(child) >= indexOfChild) .Sum(child => child.ActualHeight - child.CalculatedDockMinHeight()); panelFraction = (fixedChild.ActualHeight - fixedChild.CalculatedDockMinHeight()) / (availableHeightLeft > 0 ? availableHeightLeft : 1); } else { var fixedHeightLeft = fixedPanels.Where(child => fixedPanels.IndexOf(child) >= indexOfChild) .Sum(child => child.FixedDockHeight); panelFraction = fixedChild.FixedDockHeight / (fixedHeightLeft > 0 ? fixedHeightLeft : 1); } var childActualHeight = fixedChild.ActualHeight; var heightToSet = Math.Max(Math.Round(delta * panelFraction + fixedChild.ActualHeight), fixedChild.CalculatedDockMinHeight()); fixedChild.ResizableAbsoluteDockHeight = heightToSet; delta -= heightToSet - childActualHeight; } } } else { var delta = availableSize.Width - currentSize.Width; var relativeDelta = relativePanels.Sum(child => child.ActualWidth - child.CalculatedDockMinWidth()); delta += relativeDelta; foreach (var fixedChild in fixedPanels) { if (minimumSize.Width >= availableSize.Width) { fixedChild.ResizableAbsoluteDockWidth = fixedChild.CalculatedDockMinWidth(); } else if (preferredMinimumSize.Width <= availableSize.Width) { fixedChild.ResizableAbsoluteDockWidth = fixedChild.FixedDockWidth; } else { double panelFraction; var indexOfChild = fixedPanels.IndexOf(fixedChild); if (delta < 0) { var availableWidthLeft = fixedPanels.Where(child => fixedPanels.IndexOf(child) >= indexOfChild) .Sum(child => child.ActualWidth - child.CalculatedDockMinWidth()); panelFraction = (fixedChild.ActualWidth - fixedChild.CalculatedDockMinWidth()) / (availableWidthLeft > 0 ? availableWidthLeft : 1); } else { var fixedWidthLeft = fixedPanels.Where(child => fixedPanels.IndexOf(child) >= indexOfChild) .Sum(child => child.FixedDockWidth); panelFraction = fixedChild.FixedDockWidth / (fixedWidthLeft > 0 ? fixedWidthLeft : 1); } var childActualWidth = fixedChild.ActualWidth; var widthToSet = Math.Max(Math.Round(delta * panelFraction + fixedChild.ActualWidth), fixedChild.CalculatedDockMinWidth()); fixedChild.ResizableAbsoluteDockWidth = widthToSet; delta -= widthToSet - childActualWidth; } } } foreach (var child in InternalChildren.OfType <IAdjustableSizeLayout>()) { child.AdjustFixedChildrenPanelSizes(availableSize); } }
public Size GetDimensions() { if (_size == null) { if (_fs.FileExists(Path)) { EnsureFileSupportsResizing(); using (var fs = _fs.OpenFile(Path)) { using (var image = Image.FromStream(fs)) { var fileWidth = image.Width; var fileHeight = image.Height; _size = new Size(fileWidth, fileHeight); } } } else { _size = new Size(-1, -1); } } return _size.Value; }
private void ReportViewerForm_FormClosing(object sender, FormClosingEventArgs e) { #if DEBUG if (_report != null) _report.Repository.FlushTranslationUsage(); #endif if (_report != null && _report.IsExecuting) _report.CancelExecution(); LastSize = Size; LastLocation = Location; if (_exitOnClose) Application.Exit(); }
protected override Size MeasureOverride(Size constraint) { Size size = new Size(); foreach (UIElement child in this.Children) { child.Measure(constraint); size.Width = Math.Max(child.DesiredSize.Width, size.Width); size.Height = Math.Max(child.DesiredSize.Height, size.Height); } if (this.previousSize == null) { this.previousSize = size; this.SelfLayoutScaleX = size.Width; this.SelfLayoutScaleY = size.Height; } else { if (this.previousSize.HasValue && this.previousSize.Value != size) { Storyboard story = new Storyboard(); DoubleAnimation doubleAnimation; doubleAnimation = new DoubleAnimation() { From = this.SelfLayoutScaleX, To = size.Width, Duration = new Duration(this.LayoutAnimationDuration), DecelerationRatio = 1 }; Storyboard.SetTarget(doubleAnimation, this); Storyboard.SetTargetProperty(doubleAnimation, new PropertyPath(LayoutClipBox.SelfLayoutScaleXProperty)); story.Children.Add(doubleAnimation); doubleAnimation = new DoubleAnimation() { From = this.SelfLayoutScaleY, To = size.Height, Duration = new Duration(this.LayoutAnimationDuration), DecelerationRatio = 1 }; Storyboard.SetTarget(doubleAnimation, this); Storyboard.SetTargetProperty(doubleAnimation, new PropertyPath(LayoutClipBox.SelfLayoutScaleYProperty)); story.Children.Add(doubleAnimation); if (this.selfscale != null) { this.selfscale.Pause(); this.selfscale.Remove(); } this.selfscale = story; this.selfscale.Begin(); this.previousSize = size; } } return new Size(this.SelfLayoutScaleX * this.LayoutScaleX, this.SelfLayoutScaleY * this.LayoutScaleY); }
protected override Size ArrangeOverride(Size finalSize) { _size = finalSize; if (_state == FlipperState.Uninitialized) { InitializeIfReady(); } else { for (int i = 0; i < VirtualPoolSize; i++) { _containers[i].SetSize(_size.Value); } ResetGeometry(); UpdateVirtualizedItemPositions(); UpdateViewport(); } return base.ArrangeOverride(finalSize); }
protected override void OnMouseDown(MouseEventArgs e) { mouseGrabOffset = new Size(e.Location); base.OnMouseDown(e); }
protected override void OnLayoutCore(bool changed, int left, int top, int right, int bottom) { base.OnLayoutCore(changed, left, top, right, bottom); Size newSize; if (ArrangeLogicalSize is Rect als) { // If the parent element is from managed code, // we can recover the "Arrange" with double accuracy. // We use that because the conversion to android's "int" is loosing too much precision. newSize = new Size(als.Width, als.Height); } else { // Here the "arrange" is coming from a native element, // so we convert those measurements to logical ones. newSize = new Size(right - left, bottom - top).PhysicalToLogicalPixels(); } if (this.Log().IsEnabled(Microsoft.Extensions.Logging.LogLevel.Debug)) { this.Log().DebugFormat( "[{0}/{1}] OnLayoutCore({2}, {3}, {4}, {5}) (parent: {5},{6})", GetType(), Name, left, top, right, bottom, MeasuredWidth, MeasuredHeight ); } var previousSize = _actualSize; _actualSize = newSize; if ( // If the layout has changed, but the final size has not, this is just a translation. // So unless there was a layout requested, we can skip arranging the children. (changed && _lastLayoutSize != newSize) // Even if nothing changed, but a layout was requested, arrange the children. || IsLayoutRequested ) { _lastLayoutSize = newSize; var finalRect = new Rect(0, 0, newSize.Width, newSize.Height); OnBeforeArrange(); _layouter.Arrange(finalRect); OnAfterArrange(); } if (previousSize != newSize) { SizeChanged?.Invoke(this, new SizeChangedEventArgs(this, previousSize, newSize)); _renderTransform?.UpdateSize(newSize); } }
public void StartCaputre(int timeOutSeconds, Size?defaultSize) { var mask = new MaskWindow(this); mask.Show(timeOutSeconds, defaultSize); }
public SizeArgument(Size?size) { Size = size; }
void this_SizeChanged(object sender, SizeChangedEventArgs e) { currentSize = e.NewSize; UpdateFontSize(e.NewSize, FontSizePercent); }
static void SaveAsImage(FrameworkElement element, ScaleTransform scaleTransform, string dirName, string fileName, string extension, bool isBlack = false, Size?size = null) { scaleTransform.ScaleX = size.HasValue ? size.Value.Width / element.ActualWidth : 1.0; scaleTransform.ScaleY = size.HasValue ? size.Value.Height / element.ActualHeight : 1.0; var bitmap = size.HasValue ? BitmapUtility.CreateImage(element, size.Value) : BitmapUtility.CreateImage(element); var filePath = CreateFilePath(dirName, fileName, extension, isBlack, size); BitmapUtility.SaveImage(filePath, bitmap); }
private void SmartCopyForm_FormClosed(object sender, FormClosedEventArgs e) { _lastReports = reportsListBox.Items.OfType<PropertyItem>().ToList(); LastSize = Size; LastLocation = Location; }
static string CreateFilePath(string dirName, string fileName, string extension, bool isBlack = false, Size?size = null) { var sizeString = size.HasValue ? string.Format("-{0}x{1}", size.Value.Width, size.Value.Height) : ""; return(Path.Combine(dirName, string.Format("{0}{2}{3}{1}", fileName, extension, isBlack ? "-black" : "", sizeString))); }
/// <summary> /// スクロールバーサイズ設定時 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void imageScrollViewr_SizeChanged(object sender, SizeChangedEventArgs e) { Debug.WriteLine("imageScrollViewr_SizeChanged"); m_contentSize = e.NewSize; updateImage(imagePivot.SelectedItem as PivotItem, m_contentSize, true); }
/// <summary> /// Asynchronously retrieves an image resource, scaled to the target dimensions. /// </summary> /// <param name="ct"></param> /// <param name="resourceId"></param> /// <param name="targetSize"></param> /// <returns></returns> private async Task <Bitmap> FetchResourceWithDownsampling(CancellationToken ct, int resourceId, Size?targetSize) { var key = Tuple.Create(resourceId, targetSize); Bitmap bitmap; if (!_resourceCache.TryGetValue(key, out bitmap)) { try { while (_resourceCacheLock) { await Task.Yield(); } _resourceCacheLock = true; if (!_resourceCache.TryGetValue(key, out bitmap)) { var options = new BitmapFactory.Options(); if (targetSize.HasValue) { //Get image bounds only options.InJustDecodeBounds = true; BitmapFactory.DecodeResource(ContextHelper.Current.Resources, resourceId, options); //Get downsampling to use. Note we're not worried about rounding, DecodeResource will round down to nearest power of 2 anyway - http://developer.android.com/training/displaying-bitmaps/load-bitmap.html float scale = options.InDensity != 0 && options.InTargetDensity != 0 ? //http://stackoverflow.com/questions/15167794/bitmapfactory-optionsoutwidth-returns-different-size-than-actual-bitmap (float)options.InTargetDensity / (float)options.InDensity : 1; options.InSampleSize = (int)Math.Min(options.OutWidth * scale / targetSize.Value.Width, options.OutHeight * scale / targetSize.Value.Height); options.InJustDecodeBounds = false; } bitmap = await BitmapFactory.DecodeResourceAsync(ContextHelper.Current.Resources, resourceId, options); _resourceCache.Add(key, bitmap); } } finally { _resourceCacheLock = false; } } return(bitmap); }
/// <summary> /// Saves a 'png' thumbnail from the input video to drive /// </summary> /// <param name="source">Source video analysis</param> /// <param name="output">Output video file path</param> /// <param name="captureTime">Seek position where the thumbnail should be taken.</param> /// <param name="size">Thumbnail size. If width or height equal 0, the other will be computed automatically.</param> /// <returns>Bitmap with the requested snapshot.</returns> public static Task <bool> SnapshotAsync(IMediaAnalysis source, string output, Size?size = null, TimeSpan?captureTime = null) { if (Path.GetExtension(output) != FileExtension.Png) { output = Path.GetFileNameWithoutExtension(output) + FileExtension.Png; } var(arguments, outputOptions) = BuildSnapshotArguments(source, size, captureTime); return(arguments .OutputToFile(output, true, outputOptions) .ProcessAsynchronously()); }
internal VisualizationInfo(IWordsColoring coloring, Size?size = null, string font = null) { this.size = size; this.font = Fonts.GetFont(font); wordsColoring = coloring; }
public Pad(Size?toDimensions, Point?atPosition) : this() { Dimensions = toDimensions; Offset = atPosition; }
internal bool TryGetSize(out Size size) { size = this.size ?? Size.Empty; return(this.size != null); }
/// <summary> /// Changes a texture's size to match the desired size for samplers, /// or increases a texture's size to fit the region indicated by a size hint. /// </summary> /// <param name="info">The desired texture info</param> /// <param name="texture">The texture to resize</param> /// <param name="isSamplerTexture">True if the texture will be used for a sampler, false otherwise</param> /// <param name="sizeHint">A hint indicating the minimum used size for the texture</param> private void ChangeSizeIfNeeded(TextureInfo info, Texture texture, bool isSamplerTexture, Size?sizeHint) { if (isSamplerTexture) { // If this is used for sampling, the size must match, // otherwise the shader would sample garbage data. // To fix that, we create a new texture with the correct // size, and copy the data from the old one to the new one. if (!TextureCompatibility.SizeMatches(texture.Info, info)) { texture.ChangeSize(info.Width, info.Height, info.DepthOrLayers); } } else if (sizeHint != null) { // A size hint indicates that data will be used within that range, at least. // If the texture is smaller than the size hint, it must be enlarged to meet it. // The maximum size is provided by the requested info, which generally has an aligned size. int width = Math.Max(texture.Info.Width, Math.Min(sizeHint.Value.Width, info.Width)); int height = Math.Max(texture.Info.Height, Math.Min(sizeHint.Value.Height, info.Height)); if (texture.Info.Width != width || texture.Info.Height != height) { texture.ChangeSize(width, height, info.DepthOrLayers); } } }
protected override Size MeasureOverride(Size availableSize) { AvailableSize = availableSize; return(availableSize); }
protected override void WndProc(ref Message m) { if (!IsDesignMode) { switch (m.Msg) { case NativeMethods.WindowsMessage.WM_GETMINMAXINFO: { var mmi = (NativeMethods.MINMAXINFO)Marshal.PtrToStructure(m.LParam, typeof(NativeMethods.MINMAXINFO)); BORDER_X = -mmi.ptMaxPosition.x - BorderSize; BORDER_Y = -mmi.ptMaxPosition.y - BorderSize; maxPadding = new Padding(BORDER_X, BORDER_Y, BORDER_X, BORDER_Y); base.WndProc(ref m); } break; case NativeMethods.WindowsMessage.WM_SHOWWINDOW: { if (StartPosition == FormStartPosition.CenterParent && Owner != null) { Location = new Point(Owner.Location.X + Owner.Width / 2 - Width / 2, Owner.Location.Y + Owner.Height / 2 - Height / 2); } else if (StartPosition == FormStartPosition.CenterScreen || (StartPosition == FormStartPosition.CenterParent && Owner == null)) { var currentScreen = Screen.FromHandle(this.Handle); Location = new Point(currentScreen.WorkingArea.Left + (currentScreen.WorkingArea.Width / 2 - this.Width / 2), currentScreen.WorkingArea.Top + (currentScreen.WorkingArea.Height / 2 - this.Height / 2)); } Activate(); BringToFront(); base.WndProc(ref m); } break; case NativeMethods.WindowsMessage.WM_NCHITTEST: { if (m.Result == NativeMethods.FALSE && Resizable && Borderless) { Point p = PointToClient(new Point(NativeMethods.LoWord(m.LParam.ToInt32()), NativeMethods.HiWord(m.LParam.ToInt32()))); var hit = GetDirection(p.X, p.Y); SetResizeMethod(hit); m.Result = (IntPtr)hit; } else { base.WndProc(ref m); } } break; case NativeMethods.WindowsMessage.WM_SIZE: { if (Borderless) { var msg = m.WParam.ToInt32(); if (msg == 0 && fullClientModePadding.HasValue) { Padding = fullClientModePadding.Value; fullClientModePadding = null; } else if (msg == 2) { if (fullClientModePadding == null) { fullClientModePadding = Padding; } Padding = maxPadding; } } if (browser != null && browser.IsHandleCreated) { var x = NativeMethods.LoWord(m.LParam.ToInt32()); var y = NativeMethods.HiWord(m.LParam.ToInt32()); var js = string.Format(JS_WINDOW_STATE_CHANGED, m.WParam, x, y); browser.ExecuteJavascript(js); } base.WndProc(ref m); } break; case NativeMethods.WindowsMessage.WM_SYSCOMMAND: { if (Borderless) { var msg = m.WParam.ToInt32(); if (msg == NativeMethods.SysCommand.SC_MINIMIZE || msg == NativeMethods.SysCommand.SC_MAXIMIZE) { if (WindowState != FormWindowState.Minimized && WindowState != FormWindowState.Maximized) { windowOriginalSize = ClientSize; } } } base.WndProc(ref m); } break; case NativeMethods.WindowsMessage.WM_MOVE: { if (browser != null && browser.BrowserHost != null) { browser.BrowserHost.NotifyScreenInfoChanged(); } base.WndProc(ref m); } break; default: { if (Borderless) { if (IsNonclientMode) { NonclientModeWndProc(ref m); } else { DwmModeWndProc(ref m); } } else { base.WndProc(ref m); } } break; } } else { base.WndProc(ref m); } }
// ComboBoxCustom public Entry(string nam, string t, System.Drawing.Point p, System.Drawing.Size s, string tt, List <string> comboitems, Size?sz = null) { controltype = typeof(ExtendedControls.ComboBoxCustom); text = t; pos = p; size = s; tooltip = tt; controlname = nam; comboboxitems = string.Join(",", comboitems); comboboxdropdownsize = sz; }
/// <summary> /// /// </summary> /// <param name="rectList"></param> /// <param name="foundWeights"></param> /// <param name="foundScales"></param> /// <param name="detectThreshold"></param> /// <param name="winDetSize"></param> public static void GroupRectanglesMeanshift(IList <Rect> rectList, out double[] foundWeights, out double[] foundScales, double detectThreshold = 0.0, Size?winDetSize = null) { if (rectList == null) { throw new ArgumentNullException("rectList"); } Size winDetSize0 = winDetSize.GetValueOrDefault(new Size(64, 128)); using (var rectListVec = new VectorOfRect(rectList)) using (var foundWeightsVec = new VectorOfDouble()) using (var foundScalesVec = new VectorOfDouble()) { NativeMethods.objdetect_groupRectangles_meanshift( rectListVec.CvPtr, foundWeightsVec.CvPtr, foundScalesVec.CvPtr, detectThreshold, winDetSize0); ClearAndAddRange(rectList, rectListVec.ToArray()); foundWeights = foundWeightsVec.ToArray(); foundScales = foundScalesVec.ToArray(); } }
public NodeViewModel(WorkspaceViewModel workspaceViewModel, NodeModel logic, Size preferredSize) : this(workspaceViewModel, logic) { // preferredSize is set when a node needs to have a fixed size PreferredSize = preferredSize; }
void OnPrintTaskCompleted(PrintTask sender, PrintTaskCompletedEventArgs args) { this.pageSize = null; this.imageableRect = null; this.document = null; this.pages = null; }
internal async Task <Stream> RetrieveDatasetRendered(WadoDataSetModel query, Size?size) { var stm = await RestClient.queryRenderedDicomFile(UrlBuilder.Combine(ServiceConfig.WadoRsServiceUrl, WadoDataSetConverter.ToWadoRenderedRsQueryUrl(query)), null, size); return(stm); }
async void UpdateImageSize() { imageSize = null; imageSize = await DependencyService.Get<ImageService>().Measure(Source); InvalidateMeasure(); }
protected override void OnMouseUp(MouseEventArgs e) { mouseGrabOffset = null; ResizingLeft = false; ResizingWidth = false; ResizingTop = false; ResizingHeight = false; base.OnMouseUp(e); }
/// <summary> /// Carries out a measure of the control. /// </summary> /// <param name="availableSize">The available size for the control.</param> public void Measure(Size availableSize) { if (double.IsNaN(availableSize.Width) || double.IsNaN(availableSize.Height)) { throw new InvalidOperationException("Cannot call Measure using a size with NaN values."); } if (!IsMeasureValid || _previousMeasure != availableSize) { var previousDesiredSize = DesiredSize; var desiredSize = default(Size); IsMeasureValid = true; try { _measuring = true; desiredSize = MeasureCore(availableSize).Constrain(availableSize); } finally { _measuring = false; } if (IsInvalidSize(desiredSize)) { throw new InvalidOperationException("Invalid size returned for Measure."); } DesiredSize = desiredSize; _previousMeasure = availableSize; Logger.Verbose(LogArea.Layout, this, "Measure requested {DesiredSize}", DesiredSize); if (DesiredSize != previousDesiredSize) { this.GetVisualParent<ILayoutable>()?.ChildDesiredSizeChanged(this); } } }
/// <summary> /// Carries out a measure of the control. /// </summary> /// <param name="availableSize">The available size for the control.</param> /// <param name="force"> /// If true, the control will be measured even if <paramref name="availableSize"/> has not /// changed from the last measure. /// </param> public void Measure(Size availableSize, bool force = false) { if (double.IsNaN(availableSize.Width) || double.IsNaN(availableSize.Height)) { throw new InvalidOperationException("Cannot call Measure using a size with NaN values."); } if (force || !IsMeasureValid || _previousMeasure != availableSize) { IsMeasureValid = true; var desiredSize = MeasureCore(availableSize).Constrain(availableSize); if (IsInvalidSize(desiredSize)) { throw new InvalidOperationException("Invalid size returned for Measure."); } DesiredSize = desiredSize; _previousMeasure = availableSize; _layoutLog.Verbose("Measure requested {DesiredSize}", DesiredSize); } }
void SQLEditorForm_FormClosed(object sender, FormClosedEventArgs e) { LastSize = Size; LastLocation = Location; }
public NodeViewModel(WorkspaceViewModel workspaceViewModel, NodeModel logic, Size preferredSize) :this(workspaceViewModel, logic) { // preferredSize is set when a node needs to have a fixed size PreferredSize = preferredSize; }
private Size GetItemSize(Size availableSize) { this.lastItemSize = Comics.Defaults.DynamicSize(availableSize.Width); return((Size)this.lastItemSize); }
public override void AttachEvent(string id) { var wpfcontrol = Control as swc.Control; switch (id) { case Eto.Forms.Control.MouseMoveEvent: if (UseMousePreview) { ContainerControl.PreviewMouseMove += HandleMouseMove; } else { ContainerControl.MouseMove += HandleMouseMove; } break; case Eto.Forms.Control.MouseDownEvent: if (UseMousePreview) { ContainerControl.PreviewMouseDown += HandleMouseDown; } else { ContainerControl.MouseDown += HandleMouseDown; } HandleEvent(Eto.Forms.Control.MouseUpEvent); break; case Eto.Forms.Control.MouseDoubleClickEvent: if (wpfcontrol != null) { if (UseMousePreview) { wpfcontrol.PreviewMouseDoubleClick += HandleMouseDoubleClick; } else { wpfcontrol.MouseDoubleClick += HandleMouseDoubleClick; } } else { HandleEvent(Eto.Forms.Control.MouseDownEvent); } break; case Eto.Forms.Control.MouseUpEvent: if (UseMousePreview) { ContainerControl.PreviewMouseUp += HandleMouseUp; } else { ContainerControl.MouseUp += HandleMouseUp; } HandleEvent(Eto.Forms.Control.MouseDownEvent); break; case Eto.Forms.Control.MouseEnterEvent: ContainerControl.MouseEnter += (sender, e) => { if (isMouseOver != Control.IsMouseOver) { var args = e.ToEto(Control); Widget.OnMouseEnter(args); e.Handled = args.Handled; isMouseOver = Control.IsMouseOver; } }; break; case Eto.Forms.Control.MouseLeaveEvent: ContainerControl.MouseLeave += (sender, e) => { if (isMouseOver != Control.IsMouseOver) { var args = e.ToEto(Control); Widget.OnMouseLeave(args); e.Handled = args.Handled; isMouseOver = Control.IsMouseOver; } }; break; case Eto.Forms.Control.MouseWheelEvent: ContainerControl.PreviewMouseWheel += (sender, e) => { var args = e.ToEto(Control); Widget.OnMouseLeave(args); e.Handled = args.Handled; }; break; case Eto.Forms.Control.SizeChangedEvent: ContainerControl.SizeChanged += (sender, e) => { newSize = e.NewSize.ToEtoSize(); // so we can report this back in Control.Size Widget.OnSizeChanged(EventArgs.Empty); newSize = null; }; break; case Eto.Forms.Control.KeyDownEvent: if (UseKeyPreview) { Control.PreviewKeyDown += HandleKeyDown; Control.PreviewTextInput += HandleTextInput; } else { Control.KeyDown += HandleKeyDown; Control.TextInput += HandleTextInput; } break; case Eto.Forms.Control.KeyUpEvent: Control.KeyUp += (sender, e) => { var args = e.ToEto(KeyEventType.KeyUp); Widget.OnKeyUp(args); e.Handled = args.Handled; }; break; case Eto.Forms.Control.ShownEvent: ContainerControl.IsVisibleChanged += (sender, e) => { if ((bool)e.NewValue) { Widget.OnShown(EventArgs.Empty); } }; break; case Eto.Forms.Control.GotFocusEvent: Control.GotFocus += (sender, e) => Widget.OnGotFocus(EventArgs.Empty); break; case Eto.Forms.Control.LostFocusEvent: Control.LostFocus += (sender, e) => Widget.OnLostFocus(EventArgs.Empty); break; default: base.AttachEvent(id); break; } }
internal void HandleItemSizingStrategy(Action <Size> reportMeasure, Size?size) { _reportMeasure = reportMeasure; _size = size; }
void GetPageSize(PaginateEventArgs e) { if (this.pageSize == null) { PrintPageDescription description = e.PrintTaskOptions.GetPageDescription( (uint)e.CurrentPreviewPageNumber); this.pageSize = description.PageSize; this.imageableRect = description.ImageableRect; } }
private void MoveChild(UIElement dragedChild) { var screenPos = new Win32.POINT(); if (!Win32.GetCursorPos(ref screenPos)) { return; } var posToPanel = AssociatedObject.PointFromScreen(new Point(screenPos.X, screenPos.Y)); var dragedElement = dragedChild as FrameworkElement; var childRect = new Rect(posToPanel.X - _cacheMouseDownToChildPos.X, DisabledYPosition ? _cacheChildToPanelPos.Y : (posToPanel.Y - _cacheMouseDownToChildPos.Y), dragedElement.ActualWidth, dragedElement.ActualHeight); //find the child which has max overlapping area with dragedChild Size? maxOverlapSize = null; FrameworkElement maxOverlapChild = null; foreach (FrameworkElement fe in AssociatedObject.Children) { if (fe == dragedElement) { continue; } var sp = fe.TranslatePoint(new Point(), AssociatedObject); var overlapSize = GetOverlapSize(new Rect(sp, new Point(sp.X + fe.ActualWidth, sp.Y + fe.ActualHeight)), childRect); if (overlapSize.IsEmpty) { continue; } if (maxOverlapSize == null || DoubleUtil.GreaterThan(overlapSize.Width * overlapSize.Height, maxOverlapSize.Value.Width * maxOverlapSize.Value.Height)) { maxOverlapSize = overlapSize; maxOverlapChild = fe; } } //check the overlapping area whether match the exchanging child condition if (!maxOverlapSize.HasValue || maxOverlapSize.Value.IsEmpty) { return; } if (DoubleUtil.GreaterThanOrClose(maxOverlapSize.Value.Width, maxOverlapChild.ActualWidth / 2) && DoubleUtil.GreaterThanOrClose(maxOverlapSize.Value.Height, maxOverlapChild.ActualHeight / 2)) { var targetIndex = AssociatedObject.Children.IndexOf(maxOverlapChild); if (IsFromItemsPanelTemplate) { var sourceIndex = AssociatedObject.Children.IndexOf(dragedChild); if (ItemsContainer.ItemsSource != null) { if (MoveItemFromItemsSource != null) { MoveItemFromItemsSource(sourceIndex, targetIndex); //if use ObservableCollection.Move(...) to exchange position, follow code is unnecessary. //else use ObservableCollection.RemoveAt(...) and ObservableCollection.Insert(...) to exchange position, follow code is necessary. _dragedChild = AssociatedObject.Children[targetIndex]; _dragedChild.Opacity = 0; } } else { var sourceItem = ItemsContainer.Items[sourceIndex]; ItemsContainer.Items.RemoveAt(sourceIndex); ItemsContainer.Items.Insert(targetIndex, sourceItem); _dragedChild = AssociatedObject.Children[targetIndex]; _dragedChild.Opacity = 0; } } else { AssociatedObject.Children.Remove(dragedChild); AssociatedObject.Children.Insert(targetIndex, dragedChild); } } }
private void OnMediaViewerSizeChanged(object sender, SizeChangedEventArgs e) { //if (GetElementCount() == 0) // return; _size = e.NewSize; if (GetElementCount() == 0) return; if (_state == MediaViewerState.Uninitialized) { InitializeVirtualizationIfReady(); } else { UpdateVirtualizedItemSizes(); ResetItemLayout(); if (_displayedElementIndex != null) { ScrollOffset = -1 * CalculateElementOffset(_displayedElementIndex.Value); } else { ScrollOffset = 0; } } }
public Bubble(Compositor Compositor, CanvasDevice canvasDevice, CompositionGraphicsDevice graphicsDevice, Size TargetSize, Color Color, TimeSpan Duration, bool OnTop, Size?Size = null, bool?IsFill = null) { _compositor = Compositor; _canvasDevice = canvasDevice; _graphicsDevice = graphicsDevice; _visual = Compositor.CreateSpriteVisual(); if (!IsFill.HasValue) { var tmp = rnd.Next(2); IsFill = tmp > 0; } if (Size.HasValue) { this.Size = Size.Value.ToVector2(); } else { var maxRadius = (int)Math.Min(TargetSize.Width, TargetSize.Height); if (IsFill.Value) { this.Size = new Vector2(rnd.Next(maxRadius / 7, maxRadius / 4)); } else { this.Size = new Vector2(rnd.Next(maxRadius / 6, maxRadius / 3)); } } Draw(IsFill.Value, Color); Offset = new Vector3((float)TargetSize.Width / 2, (float)TargetSize.Height / 2, 0f); _visual.Size = this.Size; _visual.Offset = Offset; _visual.Scale = Vector3.Zero; _visual.BindCenterPoint(); CreateAnimation(TargetSize, _visual.Offset, OnTop, Duration); }