private void ButtonSave_Click(object sender, RoutedEventArgs e) { var rect = new Rect { Width = 512, Height = 384 }; var dv = new DrawingVisual(); var dc = dv.RenderOpen(); dc.PushTransform(new TranslateTransform(-rect.X, -rect.Y)); dc.DrawRectangle(InkCanvasMain.Background, null, rect); InkCanvasMain.Strokes.Draw(dc); dc.Close(); var rtb = new RenderTargetBitmap((int)rect.Width, (int)rect.Height, 96, 96, PixelFormats.Default); rtb.Render(dv); var enc = new PngBitmapEncoder(); enc.Frames.Add(BitmapFrame.Create(rtb)); var fn = TextBoxFileName.Text; if (!fn.EndsWith(".png", StringComparison.OrdinalIgnoreCase)) fn += ".png"; using (Stream s = File.Create(TegakiImageFolder + "/" + fn)) { enc.Save(s); } ((TegakiWindowViewModel)DataContext).AddToMediaList(System.IO.Path.GetFullPath(TegakiImageFolder + "/" + fn)); Close(); }
private void Create3DViewPort() { var hvp3d = new HelixViewport3D(); Viewport3D vp3d = new Viewport3D(); var lights = new DefaultLights(); var tp = new Teapot(); hvp3d.Children.Add(lights); hvp3d.Children.Add(tp); vp3d = hvp3d.Viewport; tata.Children.Add(vp3d); // comenter ca pour test /* MEGA TEST DE L'ESPACE SUBSAHARIEN */ RenderTargetBitmap bmp = new RenderTargetBitmap(800, 800, 96, 96, PixelFormats.Pbgra32); var rect = new Rect(0, 0, 800, 800); vp3d.Measure(new Size(800, 800)); vp3d.Arrange(rect); vp3d.InvalidateVisual(); bmp.Render(vp3d); PngBitmapEncoder png = new PngBitmapEncoder(); png.Frames.Add(BitmapFrame.Create(bmp)); String filepath = "C:\\Users\\Remi\\Desktop\\canardmasque.png"; using (Stream stm = File.Create(filepath)) { png.Save(stm); } }
protected override void DrawTile(DrawingContext dc, Rect TileRect) { if (!_tileImage.IsReady) dc.DrawRectangle(Brushes.LemonChiffon, null, TileRect); else dc.DrawImage(_tileImage.Image, TileRect); }
protected override void OnRender(DrawingContext drawingContext) { FoldingMargin margin = VisualParent as FoldingMargin; Pen activePen = new Pen(margin.SelectedFoldingMarkerBrush, 1); Pen inactivePen = new Pen(margin.FoldingMarkerBrush, 1); activePen.StartLineCap = inactivePen.StartLineCap = PenLineCap.Square; activePen.EndLineCap = inactivePen.EndLineCap = PenLineCap.Square; Size pixelSize = PixelSnapHelpers.GetPixelSize(this); Rect rect = new Rect(pixelSize.Width / 2, pixelSize.Height / 2, this.RenderSize.Width - pixelSize.Width, this.RenderSize.Height - pixelSize.Height); drawingContext.DrawRectangle( IsMouseDirectlyOver ? margin.SelectedFoldingMarkerBackgroundBrush : margin.FoldingMarkerBackgroundBrush, IsMouseDirectlyOver ? activePen : inactivePen, rect); double middleX = rect.Left + rect.Width / 2; double middleY = rect.Top + rect.Height / 2; double space = PixelSnapHelpers.Round(rect.Width / 8, pixelSize.Width) + pixelSize.Width; drawingContext.DrawLine(activePen, new Point(rect.Left + space, middleY), new Point(rect.Right - space, middleY)); if (!isExpanded) { drawingContext.DrawLine(activePen, new Point(middleX, rect.Top + space), new Point(middleX, rect.Bottom - space)); } }
public static Rect RectZoomX(Rect rect, Point zoomCenter, double ratio) { Rect res = rect; res.X = zoomCenter.X - (zoomCenter.X - rect.X) * ratio; res.Width = rect.Width * ratio; return res; }
public static Rect LogicalRectToDevice(Rect logicalRectangle) { Point topLeft = LogicalPixelsToDevice(new Point(logicalRectangle.Left, logicalRectangle.Top)); Point bottomRight = LogicalPixelsToDevice(new Point(logicalRectangle.Right, logicalRectangle.Bottom)); return new Rect(topLeft, bottomRight); }
public override void Update() { Console.WriteLine("update"); MonitorRect = new Rect(50,50,150,200); WorkRect = new Rect(50, 50, 150, 200); Name = "Changed"; }
internal static Rect GetAutoConnectHitRect(DependencyObject target) { Size size = FreeFormPanel.GetChildSize(target); Point location = FreeFormPanel.GetLocation(target); Rect rect = new Rect(new Point(location.X - HitRegionOffset, location.Y - HitRegionOffset), new Size(size.Width + (HitRegionOffset * 2), size.Height + (HitRegionOffset * 2))); return rect; }
private void ReadWaypointId() { var actData = (Mooege.Common.MPQ.FileFormats.Act)MPQStorage.Data.Assets[SNOGroup.Act][70015].Data; var wayPointInfo = actData.WayPointInfo; var proximity = new Rect(this.Position.X - 1.0, this.Position.Y - 1.0, 2.0, 2.0); var scenes = this.World.QuadTree.Query<Scene>(proximity); if (scenes.Count == 0) return; // TODO: fixme! /raist var scene = scenes[0]; // Parent scene /fasbat if (scenes.Count == 2) // What if it's a subscene? /fasbat { if (scenes[1].ParentChunkID != 0xFFFFFFFF) scene = scenes[1]; } for (int i = 0; i < wayPointInfo.Length; i++) { if (wayPointInfo[i].SNOLevelArea == -1) continue; if (scene.Specification == null) continue; foreach (var area in scene.Specification.SNOLevelAreas) { if (wayPointInfo[i].SNOWorld != this.World.WorldSNO.Id || wayPointInfo[i].SNOLevelArea != area) continue; this.WaypointId = i; break; } } }
public MainWindow(IDBOperation dbOperation) { Rect rc = SystemParameters.WorkArea;//获取工作区大小 //this.Width = 1366; //this.Height = 766; this.Width = rc.Width; this.Height = rc.Height; rcnormal = new Rect((rc.Width - 1366) / 2, (rc.Height - 766) / 2, 1366, 766); InitializeComponent(); this.dbOperation = dbOperation; //if (!FullScreenHelper.IsFullscreen(this)) //{ // FullScreenHelper.GoFullscreen(this); //} this.Loaded += new RoutedEventHandler(MainWindow_Loaded); //this.KeyDown += new KeyEventHandler(MainWindow_KeyDown); //this.StateChanged += new EventHandler(MainWindow_StateChanged); //根据分辨率判断标题字体大小 if (rc.Width < 1680) { _title_dept.FontSize = 17; _title_1.FontSize = 24; } else { _title_dept.FontSize = 22; _title_1.FontSize = 30; } }
/// <summary> /// Moves the <see cref="window"/> to the center of the given <see cref="area"/>. /// </summary> /// <param name="window">The window.</param> /// <param name="area">The aera.</param> public static void CenterToArea(this Window window, Rect area) { if (area == Rect.Empty) return; window.Left = Math.Abs(area.Width - window.Width) / 2 + area.Left; window.Top = Math.Abs(area.Height - window.Height) / 2 + area.Top; }
void CreateAndAddAdornment(ITextViewLine line, SnapshotSpan span, Brush brush, bool extendToRight) { var markerGeometry = _view.TextViewLines.GetMarkerGeometry(span); double left = 0; double width = _view.ViewportWidth + _view.MaxTextRightCoordinate; if (markerGeometry != null) { left = markerGeometry.Bounds.Left; if (!extendToRight) width = markerGeometry.Bounds.Width; } Rect rect = new Rect(left, line.Top, width, line.Height); RectangleGeometry geometry = new RectangleGeometry(rect); GeometryDrawing drawing = new GeometryDrawing(brush, new Pen(), geometry); drawing.Freeze(); DrawingImage drawingImage = new DrawingImage(drawing); drawingImage.Freeze(); Image image = new Image(); image.Source = drawingImage; Canvas.SetLeft(image, geometry.Bounds.Left); Canvas.SetTop(image, geometry.Bounds.Top); _layer.AddAdornment(AdornmentPositioningBehavior.TextRelative, span, null, image, null); }
protected override void OnRender(DrawingContext drawingContext) { Rect rect = new Rect(startPoint, endPoint); rect.Offset(-0.5d, -0.5d); drawingContext.DrawRectangle(fill, stroke, rect); }
/// <summary> /// Annotates the specified isoline collection. /// </summary> /// <param name="collection">The collection.</param> /// <param name="visible">The visible rectangle.</param> /// <returns></returns> public Collection<IsolineTextLabel> Annotate(IsolineCollection collection, Rect visible) { Collection<IsolineTextLabel> res = new Collection<IsolineTextLabel>(); foreach (var line in collection.Lines) { double way = 0; foreach (var segment in line.GetSegments()) { double length = segment.GetLength(); way += length; if (way > wayBeforeText) { way = 0; res.Add(new IsolineTextLabel { Text = line.RealValue.ToString("G2"), Position = segment.Max, Rotation = (segment.Max - segment.Min).ToAngle() }); } } } return res; }
/// <summary> /// Returns a value indicating whether a point is inside the bounding box of the element. /// </summary> /// <param name="element"></param> /// <param name="pointRelativeToElement"></param> /// <returns></returns> public static bool ContainsPoint(this FrameworkElement element, Point pointRelativeToElement) { //TODO: Silverlight allows more complex geometries than Rectangle. Rect rect = new Rect { X = 0, Y = 0, Width = element.ActualWidth, Height=element.ActualHeight }; return rect.Contains(pointRelativeToElement); }
public WpfMonitor(IntPtr handle, uint index) : base(handle, index) { MonitorRect = new Rect(0, 10, 100, 100); WorkRect = new Rect(0, 10, 100, 100); Name = "fake"; }
public SelectionMovedOrResizedStroke(CommandStack commandStack, StrokeCollection selection, Rect newrect, Rect oldrect, int editingOperationCount) : base(commandStack) { _selection = selection; _newrect = newrect; _oldrect = oldrect; _editingOperationCount = editingOperationCount; }
public static void RightClick(Rect targetRectangle) { var clickPoint = GetCenterPoint(targetRectangle); Cursor.Position = clickPoint; mouse_event(MouseEventFlags.RightDown, (uint) clickPoint.X, (uint) clickPoint.Y, 0, 0); mouse_event(MouseEventFlags.RightUp, (uint) clickPoint.X, (uint) clickPoint.Y, 0, 0); }
public static void SingleClick(Rect dragRectangle) { var startPoint = GetCenterPoint(dragRectangle); SetCursorPos(startPoint.X, startPoint.Y); mouse_event(MouseEventFlags.LeftDown, (uint)startPoint.X, (uint)startPoint.Y, 0, 0); mouse_event(MouseEventFlags.LeftUp, (uint)startPoint.X, (uint)startPoint.Y, 0, 0); }
public RenderState(Rect renderVisible, Rect visible, Rect output, RenderTo renderingType) { this.renderVisible = renderVisible; this.visible = visible; this.output = output; this.renderingType = renderingType; }
/// <summary> /// Moves and resize the <see cref="window"/> to make it fill the whole given <see cref="area"/>. /// </summary> /// <param name="window">The window.</param> /// <param name="area">The area.</param> public static void FillArea(this Window window, Rect area) { window.Width = area.Width; window.Height = area.Height; window.Left = area.Left; window.Top = area.Top; }
private void MoveThumb_DragDelta(object sender, DragDeltaEventArgs e) { if (DesignerItem.IsSelected) { _wasMoved = true; Vector shift = new Vector(e.HorizontalChange, e.VerticalChange); foreach (DesignerItem designerItem in DesignerCanvas.SelectedItems) { Rect rect = new Rect(Canvas.GetLeft(designerItem), Canvas.GetTop(designerItem), designerItem.ActualWidth, designerItem.ActualHeight); if (rect.Right + shift.X > DesignerCanvas.Width) shift.X = DesignerCanvas.Width - rect.Right; if (rect.Left + shift.X < 0) shift.X = -rect.Left; if (rect.Bottom + shift.Y > DesignerCanvas.Height) shift.Y = DesignerCanvas.Height - rect.Bottom; if (rect.Top + shift.Y < 0) shift.Y = -rect.Top; } foreach (DesignerItem designerItem in DesignerCanvas.SelectedItems) { designerItem.Element.Position += shift; designerItem.SetLocation(); } DesignerCanvas.InvalidateMeasure(); e.Handled = true; ServiceFactory.SaveService.PlansChanged = true; } }
/// <summary> /// Constructor for public RectAnimationClockResource. /// This constructor accepts the base value and AnimationClock. /// Note that since there is no current requirement that we be able to set or replace either the /// base value or the AnimationClock, this is the only way to initialize an instance of /// RectAnimationClockResource. /// Also, we currently Assert that the resource is non-null, since without mutability /// such a resource isn't needed. /// We can easily extend this class if/when new requirements arise. /// </summary> /// <param name="baseValue"> Rect - The base value. </param> /// <param name="animationClock"> AnimationClock - cannot be null. </param> public RectAnimationClockResource( Rect baseValue, AnimationClock animationClock ): base( animationClock ) { _baseValue = baseValue; }
public static Rect RectZoomY(Rect rect, Point zoomCenter, double ratio) { Rect res = rect; res.Y = zoomCenter.Y - (zoomCenter.Y - rect.Y) * ratio; res.Height = rect.Height * ratio; return res; }
protected virtual bool DoesntContain(Rect rect, double otherStart, double otherEnd) { if (rect.Equals(Rect.Empty)) return true; double center = (otherStart + otherEnd)/2; if (center.IsInvalid()) return true; return center < start || center > end; }
static TopWallpaperRenderer() { ScreenArea = new Rect(0, 0, 412, 240); var defTopAlt = new BitmapImage(); defTopAlt.BeginInit(); //defTopAlt.StreamSource = (Stream) Extensions.GetResources(@"TopAlt_DefMask\.png").First().Value; defTopAlt.UriSource = new Uri(@"pack://application:,,,/ThemeEditor.WPF;component/Resources/TopAlt_DefMask.png"); defTopAlt.CacheOption = BitmapCacheOption.OnLoad; defTopAlt.EndInit(); var bgrData = defTopAlt.GetBgr24Data(); RawTexture rTex = new RawTexture(defTopAlt.PixelWidth, defTopAlt.PixelHeight, RawTexture.DataFormat.A8); rTex.Encode(bgrData); DefaultTopSquares = new TextureViewModel(rTex, null); RenderToolFactory.RegisterTool<PenTool, Pen> (key => new Pen(new SolidColorBrush(key.Color) { Opacity = key.Opacity }, key.Width)); RenderToolFactory.RegisterTool<SolidColorBrushTool, Brush> (key => new SolidColorBrush(key.Color) { Opacity = key.Opacity }); RenderToolFactory.RegisterTool<LinearGradientBrushTool, Brush> (key => new LinearGradientBrush(key.ColorA, key.ColorB, key.Angle) { Opacity = key.Opacity }); RenderToolFactory.RegisterTool<ImageBrushTool, Brush> (key => new ImageBrush(key.Image) { TileMode = key.Mode, ViewportUnits = key.ViewportUnits, Viewport = key.Viewport, Opacity = key.Opacity }); Type ownerType = typeof(TopWallpaperRenderer); IsEnabledProperty .OverrideMetadata(ownerType, new FrameworkPropertyMetadata(false, OnIsEnabledChanged)); ClipToBoundsProperty.OverrideMetadata(ownerType, new FrameworkPropertyMetadata(true, null, (o, value) => true)); WidthProperty.OverrideMetadata(ownerType, new FrameworkPropertyMetadata(412.0, null, (o, value) => 412.0)); HeightProperty.OverrideMetadata(ownerType, new FrameworkPropertyMetadata(240.0, null, (o, value) => 240.0)); EffectProperty.OverrideMetadata(ownerType, new FrameworkPropertyMetadata(default(WarpEffect), null, (o, value) => ((TopWallpaperRenderer) o).GetWarpEffectInstance())); }
protected override Size ArrangeOverride(Size finalSize) { if (GetValues(this) != null) { double total = 0.0; for (int i = 0; i < InternalChildren.Count; i++) { total += (double)(GetValues(this)[i]); } double offsetAngle = 0.0; double radius = finalSize.Width < finalSize.Height ? finalSize.Width / 2 : finalSize.Height / 2; //radius -= 2; Point beginFigure = new Point(finalSize.Width / 2, finalSize.Height / 2); Point lineToBeforeTransform = new Point(beginFigure.X + radius, beginFigure.Y); for (int i = 0; i < InternalChildren.Count; i++) { ContentControl container = InternalChildren[i] as ContentControl; double wedgeAngle = (double)(GetValues(this)[i]) * 360 / total; RotateTransform rt = new RotateTransform(offsetAngle, beginFigure.X, beginFigure.Y); container.SetValue(PiePanel.BeginFigurePointProperty, beginFigure); container.SetValue(PiePanel.LineToPointProperty, rt.Transform(lineToBeforeTransform)); container.SetValue(PiePanel.WedgeAngleProperty, wedgeAngle); offsetAngle += wedgeAngle; Rect r = new Rect(finalSize); container.Arrange(r); } } return finalSize; }
public SilverlightComboBoxVerticalSpanCalculator(Rect combo, Rect firstItem, Rect lastItem, double percentVisible) { this.firstItem = firstItem; this.lastItem = lastItem; this.combo = combo; this.percentVisible = percentVisible; }
/// <summary> /// Hit tests given point against given layer to get features from that position. /// </summary> /// <param name="screenPoint">Screen point of that is used in hittest.</param> /// <param name="layer">Layer that is hittested against</param> /// <returns>Returns feature if there was one in the given location.</returns> /// <remarks>Hit test uses 3x3 area around given point.</remarks> public async Task<Feature> HitTestAsync(Point screenPoint, Esri.ArcGISRuntime.Layers.Layer layer) { var mapView = MapView; if (mapView != null) { if (layer is GraphicsLayer) { Rect rect = new Rect(screenPoint.X - 1, screenPoint.Y - 1, 3, 3); var glayer = (GraphicsLayer)layer; return await glayer.HitTestAsync(mapView, rect).ContinueWith(t => { return (Feature)t.Result; }); } else if (layer is FeatureLayer) { var flayer = (FeatureLayer)layer; Rect rect = new Rect(screenPoint.X - 1, screenPoint.Y - 1, 3, 3); var featureID = await flayer.HitTestAsync(mapView, rect, 1).ContinueWith(t => { return (long)t.Result.FirstOrDefault(); }); if (featureID > 0) { return await flayer.FeatureTable.QueryAsync(new long[] { featureID }) .ContinueWith(t => { return (Feature)t.Result.FirstOrDefault(); }); } } } return null; }
public static Rect DeviceRectToLogical(Rect deviceRectangle) { Point topLeft = DevicePixelsToLogical(new Point(deviceRectangle.Left, deviceRectangle.Top)); Point bottomRight = DevicePixelsToLogical(new Point(deviceRectangle.Right, deviceRectangle.Bottom)); return new Rect(topLeft, bottomRight); }
public RGBLuminanceSource(byte[] d, int W, int H, bool Is8Bit, System.Windows.Rect Region) : base(W, H) { __width = (int)Region.Width; __height = (int)Region.Height; __Region = Region; __isRegionSelect = true; //luminances = Red.Imaging.Filters.CropArea(d, W, H, Region); }
// public RGBLuminanceSource(byte[] d, int W, int H, bool Is8Bit,Rectangle Region) // commented by .net follower (http://dotnetfollower.com) public RGBLuminanceSource(byte[] d, int W, int H, bool Is8Bit, System.Windows.Rect Region) // added by .net follower (http://dotnetfollower.com) : base(W, H) { // __width = Region.Width; // commented by .net follower (http://dotnetfollower.com) // __height = Region.Height; // commented by .net follower (http://dotnetfollower.com) __width = (int)Region.Width; // added by .net follower (http://dotnetfollower.com) __height = (int)Region.Height; // added by .net follower (http://dotnetfollower.com) __Region = Region; __isRegionSelect = true; //luminances = Red.Imaging.Filters.CropArea(d, W, H, Region); }
// // Rect/Point // public static Rectangle ToXwtRect(this SW.Rect rect) { return(new Rectangle(rect.X, rect.Y, rect.Width, rect.Height)); }
public void ResetLocationAndSizeIfNotInsideAnyScreen() { LocationAndSize = LocationAndSize; }
public void WriteRect(string Section, string Key, System.Windows.Rect Value) { WriteString(Section, Key, Convert.ToString(Value)); }
private void Tesellate() { Rect = new Rect(new Point(Location.X, Location.Y), new Size(Size.X, Size.Y)); }
public void CollapsePanel() { if (IsPined) { return; } var dockDir = GetDockDirection(Dock); if (dockDir != DockDirection.None) { IsHidden = true; var area = DockScreen.MonitorArea; var mustCollapseExpandWithMove = MustCollapseExpandWithMove(Dock); DockedSensitiveArea = new w.Rect( Dock == DockName.Right ? area.Right - ScreenMouseSensitiveAreaEdgeSize : AssociatedObject.Left, Dock == DockName.Bottom ? area.Bottom - ScreenMouseSensitiveAreaEdgeSize : AssociatedObject.Top, dockDir == DockDirection.Horizontal ? ScreenMouseSensitiveAreaEdgeSize : AssociatedObject.Width, dockDir == DockDirection.Vertical ? ScreenMouseSensitiveAreaEdgeSize : AssociatedObject.Height ); var dp = dockDir == DockDirection.Horizontal ? FrameworkElement.WidthProperty : FrameworkElement.HeightProperty; var finalValue = 0d; MinWidthBackup = AssociatedObject.MinWidth; MinHeightBackup = AssociatedObject.MinHeight; AssociatedObject.MinWidth = 0; AssociatedObject.MinHeight = 0; var an = new DoubleAnimation( dockDir == DockDirection.Horizontal ? AssociatedObject.Width : AssociatedObject.Height, finalValue, new Duration(TimeSpan.FromMilliseconds(HideAnimationDuration)), FillBehavior.Stop ); an.Completed += (o, e) => { AssociatedObject.SetValue(dp, finalValue); AssociatedObject.Hide(); var t = new Thread(ScreenMouseSensitiveAreaWatcher); t.Start(); }; DoubleAnimation an2 = null; DependencyProperty dp2 = null; if (mustCollapseExpandWithMove) { double finalValue2 = dockDir == DockDirection.Horizontal ? area.Right : area.Bottom; dp2 = dockDir == DockDirection.Horizontal ? Window.LeftProperty : Window.TopProperty; an2 = new DoubleAnimation( dockDir == DockDirection.Horizontal ? AssociatedObject.Left : AssociatedObject.Top, finalValue2, new Duration(TimeSpan.FromMilliseconds(HideAnimationDuration)), FillBehavior.Stop ); an2.Completed += (o, e) => { AssociatedObject.SetValue(dp2, finalValue2); }; } if (an2 != null) { AssociatedObject.BeginAnimation(dp2, an2); } AssociatedObject.BeginAnimation(dp, an); ViewModel?.NotifyPropertyUpdated(nameof(ViewModel.IsCollapsed)); } }
public void PushGuideLines(sw.Rect rect) { PushGuideLines(rect.X, rect.Y, rect.Width, rect.Height); }
public void SetClipIntersect(RectangleF rect) { PointOutside.Check(ref rect); IntersectClip(new RectangleGeometry(rect)); }
//--------------------------------------------------------------------------------------------------------- /// <summary> /// Преобразование прямоугольника WPF прямоугольник RawRectangleF /// </summary> /// <param name="rect">Прямоугольника WPF</param> /// <returns>Прямоугольник RawRectangleF</returns> //--------------------------------------------------------------------------------------------------------- public static RawRectangleF ToRawRectangleF(this WPFBase.Rect rect) { return(new RawRectangleF((Single)rect.X, (Single)rect.Y, (Single)rect.Right, (Single)rect.Bottom)); }
//--------------------------------------------------------------------------------------------------------- /// <summary> /// Преобразование прямоугольника WPF прямоугольник RawRectangle /// </summary> /// <param name="rect">Прямоугольника WPF</param> /// <returns>Прямоугольник RawRectangle</returns> //--------------------------------------------------------------------------------------------------------- public static RawRectangle ToRawRectangle(this WPFBase.Rect rect) { return(new RawRectangle((Int32)rect.X, (Int32)rect.Y, (Int32)rect.Right, (Int32)rect.Bottom)); }
public byte[] ResizeImage(byte[] image_data, int new_width, int new_height, int quality) { BitmapImage original_image = new BitmapImage(); original_image.BeginInit(); original_image.StreamSource = new MemoryStream(image_data); original_image.EndInit(); // Calculate crop section int orig_width = original_image.PixelWidth; int orig_height = original_image.PixelHeight; float width_ratio = (float)new_width / orig_width; float height_ratio = (float)new_height / orig_height; float ratio = Math.Max(width_ratio, height_ratio); int resized_pre_crop_width = (int)Math.Round(orig_width * ratio); int resized_pre_crop_height = (int)Math.Round(orig_height * ratio); // full area to crop on resized image int resized_crop_x = resized_pre_crop_width - new_width; int resized_crop_y = resized_pre_crop_height - new_height; int cropped_width = (int)((resized_pre_crop_width - resized_crop_x) / ratio); int cropped_height = (int)((resized_pre_crop_height - resized_crop_y) / ratio); // half of area to crop on original image int crop_x = (int)(resized_crop_x / ratio / 2); int crop_y = (int)(resized_crop_y / ratio / 2); // End of calculate crop section var cropped_image = new CroppedBitmap(original_image, new Int32Rect(crop_x, crop_y, cropped_width, cropped_height)); var rect = new System.Windows.Rect(0, 0, new_width, new_height); var group = new DrawingGroup(); RenderOptions.SetBitmapScalingMode(group, BitmapScalingMode.HighQuality); group.Children.Add(new ImageDrawing(cropped_image, rect)); var drawing_visual = new DrawingVisual(); using (var drawing_context = drawing_visual.RenderOpen()) drawing_context.DrawDrawing(group); var resized_image = new RenderTargetBitmap( new_width, new_height, // Resized dimensions 96, 96, // Default DPI values PixelFormats.Default); // Default pixel format resized_image.Render(drawing_visual); JpegBitmapEncoder jbe = new JpegBitmapEncoder(); jbe.Frames.Add(BitmapFrame.Create(resized_image)); jbe.QualityLevel = quality; using (MemoryStream stream = new MemoryStream()) { jbe.Save(stream); image_data = stream.ToArray(); } return(image_data); }
static extern bool GetWindowRect(IntPtr hWnd, out System.Windows.Rect lpRect);
/// <summary> /// 模拟发送 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void btnSendMsg_Click(object sender, EventArgs e) { //根目录 AutomationElement aeDeskTop = AutomationElement.RootElement; //所有 QQ相关的窗口 var AllChildrenElement = aeDeskTop.FindAll(TreeScope.Descendants, new PropertyCondition(AutomationElement.ClassNameProperty, "TXGuiFoundation")); foreach (AutomationElement item in AllChildrenElement) { int WindowHandle = item.Current.NativeWindowHandle; string Name = item.Current.Name; if (!string.IsNullOrEmpty(Name)) { if (Name != "QQ") { #region 模拟输入消息 AndCondition pcTarget = null; pcTarget = new AndCondition( new PropertyCondition(AutomationElement.NameProperty, "输入"), new PropertyCondition(AutomationElement.ControlTypeProperty, ControlType.Edit)); AutomationElementCollection AutoEleCll = item.FindAll(TreeScope.Descendants, pcTarget); if (AutoEleCll.Count > 0) { foreach (AutomationElement Edititem in AutoEleCll) { //激活聊天主窗体 WinApi.ShowWindow(new IntPtr(WindowHandle), 1); WinApi.SetActiveWindow(new IntPtr(WindowHandle)); WinApi.SetForegroundWindow(new IntPtr(WindowHandle)); #region 获取 元素位置 //位置 System.Windows.Rect rect = Edititem.Current.BoundingRectangle; //元素 左上角位置 System.Drawing.Point tPoint = new System.Drawing.Point(); tPoint.X = Convert.ToInt32(rect.Left); tPoint.Y = Convert.ToInt32(rect.Top); //元素正中间位置 System.Drawing.Point CenterPoint = new System.Drawing.Point(); CenterPoint.X = Convert.ToInt32(rect.Left + rect.Width / 2); CenterPoint.Y = Convert.ToInt32(rect.Top + rect.Height / 2); //设置鼠标到指定位置 WinApi.SetCursorPos(CenterPoint); //模拟鼠标点击 WinApi.mouse_event(WinApi.MOUSEEVENTF_LEFTDOWN | WinApi.MOUSEEVENTF_LEFTUP, 0, 0, 0, 0); #endregion //设置窗体内容(windows 消息方式) //WinApi.SendMessage(new IntPtr(WindowHandle), WinApi.EM_SETSEL, -1, -1);// //WinApi.SendMessage(new IntPtr(WindowHandle), WinApi.WM_SETTEXT, 0, "Text"); #region 写入 数据 如果不是readonly的话 object ClipboadData = Clipboard.GetDataObject(); Clipboard.SetDataObject("模拟键盘事件,消息方式-"); //设置窗体内容(模拟键盘事件 消息方式) WinApi.keybd_event(Keys.ControlKey, 0, 0, 0); WinApi.keybd_event(Keys.V, 0, 0, 0); WinApi.keybd_event(Keys.V, 0, WinApi.KEYEVENTF_KEYUP, 0); WinApi.keybd_event(Keys.ControlKey, 0, WinApi.KEYEVENTF_KEYUP, 0); Thread.Sleep(10); //设置窗体内容(模拟键盘事件 消息方式) WinApi.keybd_event(Keys.CapsLock, 0, 0, 0); WinApi.keybd_event(Keys.CapsLock, 0, WinApi.KEYEVENTF_KEYUP, 0); Thread.Sleep(10); WinApi.keybd_event(Keys.T, 0, 0, 0); WinApi.keybd_event(Keys.T, 0, WinApi.KEYEVENTF_KEYUP, 0); Thread.Sleep(10); WinApi.keybd_event(Keys.CapsLock, 0, 0, 0); WinApi.keybd_event(Keys.CapsLock, 0, WinApi.KEYEVENTF_KEYUP, 0); WinApi.keybd_event(Keys.E, 0, 0, 0); WinApi.keybd_event(Keys.E, 0, WinApi.KEYEVENTF_KEYUP, 0); Thread.Sleep(10); WinApi.keybd_event(Keys.S, 0, 0, 0); WinApi.keybd_event(Keys.S, 0, WinApi.KEYEVENTF_KEYUP, 0); Thread.Sleep(10); WinApi.keybd_event(Keys.T, 0, 0, 0); WinApi.keybd_event(Keys.T, 0, WinApi.KEYEVENTF_KEYUP, 0); Thread.Sleep(10); #endregion } } #endregion #region 点击 发送 按钮 pcTarget = null; pcTarget = new AndCondition( new PropertyCondition(AutomationElement.NameProperty, "发送(&S)"), new PropertyCondition(AutomationElement.ControlTypeProperty, ControlType.Button)); AutoEleCll = item.FindAll(TreeScope.Descendants, pcTarget); if (AutoEleCll.Count > 0) { foreach (AutomationElement Edititem in AutoEleCll) { //激活聊天主窗体 WinApi.ShowWindow(new IntPtr(WindowHandle), 1); WinApi.SetActiveWindow(new IntPtr(WindowHandle)); WinApi.SetForegroundWindow(new IntPtr(WindowHandle)); System.Windows.Rect rect = Edititem.Current.BoundingRectangle; System.Drawing.Point tPoint = new System.Drawing.Point(); tPoint.X = Convert.ToInt32(rect.Left); tPoint.Y = Convert.ToInt32(rect.Top); System.Drawing.Point CenterPoint = new System.Drawing.Point(); CenterPoint.X = Convert.ToInt32(rect.Left + rect.Width / 2); CenterPoint.Y = Convert.ToInt32(rect.Top + rect.Height / 2); //移动鼠标至登录Button并模拟点击 System.Drawing.Point MousePoint = new System.Drawing.Point(); WinApi.GetCursorPos(out MousePoint); Rectangle rectgle = System.Windows.Forms.Screen.PrimaryScreen.Bounds; WinApi.SetCursorPos(CenterPoint); Thread.Sleep(1000); //WinApi.SetCursorPos(new System.Drawing.Point(1182,586)); //Thread.Sleep(1000); //WinApi.SetCursorPos(new System.Drawing.Point(10,10)); int dx = MousePoint.X - CenterPoint.X; int dy = MousePoint.Y - CenterPoint.Y; //读取色位 //int ss = System.Windows.Forms.Screen.PrimaryScreen.BitsPerPixel; //Math.Pow(2, ss);//2的ss次方 //WinApi.mouse_event(WinApi.MOUSEEVENTF_ABSOLUTE | WinApi.MOUSEEVENTF_MOVE, dx, dy, 0, 0); WinApi.mouse_event(WinApi.MOUSEEVENTF_LEFTDOWN | WinApi.MOUSEEVENTF_LEFTUP, 0, 0, 0, 0); //ValuePattern vpTextBox1 = (ValuePattern)Edititem.GetCurrentPattern(ValuePattern.Pattern); //string valStr = vpTextBox1.Current.Value + "Text"; //vpTextBox1.SetValue(valStr); //InvokePattern ipClickButton1 = (InvokePattern)Edititem.GetCurrentPattern(InvokePattern.Pattern); //ipClickButton1.Invoke(); //Thread.Sleep(1000); } } #endregion } } } }
/// <summary> /// 读取正在 聊天记录 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void btnTXGuiFoundation_Click(object sender, EventArgs e) { //根目录 AutomationElement aeDeskTop = AutomationElement.RootElement; //所有 QQ相关的窗口 var AllChildrenElement = aeDeskTop.FindAll(TreeScope.Descendants, new PropertyCondition(AutomationElement.ClassNameProperty, "TXGuiFoundation")); foreach (AutomationElement item in AllChildrenElement) { int WindowHandle = item.Current.NativeWindowHandle; string Name = item.Current.Name; if (!string.IsNullOrEmpty(Name)) { if (Name != "QQ") { AndCondition pcTarget = null; pcTarget = new AndCondition( new PropertyCondition(AutomationElement.NameProperty, "消息"), new PropertyCondition(AutomationElement.ControlTypeProperty, ControlType.Edit)); AutomationElementCollection AutoEleCll = item.FindAll(TreeScope.Descendants, new PropertyCondition(AutomationElement.NameProperty, "消息")); if (AutoEleCll.Count > 0) { foreach (AutomationElement Edititem in AutoEleCll) { //激活聊天主窗体 WinApi.ShowWindow(new IntPtr(WindowHandle), 1); WinApi.SetActiveWindow(new IntPtr(WindowHandle)); WinApi.SetForegroundWindow(new IntPtr(WindowHandle)); #region 获取 元素位置 //位置 System.Windows.Rect rect = Edititem.Current.BoundingRectangle; //元素 左上角位置 System.Drawing.Point tPoint = new System.Drawing.Point(); tPoint.X = Convert.ToInt32(rect.Left); tPoint.Y = Convert.ToInt32(rect.Top); //元素正中间位置 System.Drawing.Point CenterPoint = new System.Drawing.Point(); CenterPoint.X = Convert.ToInt32(rect.Left + rect.Width / 2); CenterPoint.Y = Convert.ToInt32(rect.Top + rect.Height / 2); //设置鼠标到指定位置 WinApi.SetCursorPos(CenterPoint); //模拟鼠标点击 WinApi.mouse_event(WinApi.MOUSEEVENTF_LEFTDOWN | WinApi.MOUSEEVENTF_LEFTUP, 0, 0, 0, 0); #endregion //设置窗体内容(windows 消息方式) //WinApi.SendMessage(new IntPtr(WindowHandle), WinApi.EM_SETSEL, -1, -1);// //WinApi.SendMessage(new IntPtr(WindowHandle), WinApi.WM_SETTEXT, 0, "Text"); #region 写入 数据 如果不是readonly的话 //object ClipboadData = Clipboard.GetDataObject(); //Clipboard.SetDataObject("模拟键盘事件 消息方式"); ////设置窗体内容(模拟键盘事件 消息方式) //WinApi.keybd_event(Keys.ControlKey, 0, 0, 0); //WinApi.keybd_event(Keys.V, 0, 0, 0); //WinApi.keybd_event(Keys.V, 0, WinApi.KEYEVENTF_KEYUP, 0); //WinApi.keybd_event(Keys.ControlKey, 0, WinApi.KEYEVENTF_KEYUP, 0); //Thread.Sleep(10); ////设置窗体内容(模拟键盘事件 消息方式) //WinApi.keybd_event(Keys.CapsLock, 0, 0, 0); //WinApi.keybd_event(Keys.CapsLock, 0, WinApi.KEYEVENTF_KEYUP, 0); //Thread.Sleep(10); //WinApi.keybd_event(Keys.T, 0, 0, 0); //WinApi.keybd_event(Keys.T, 0, WinApi.KEYEVENTF_KEYUP, 0); //Thread.Sleep(10); //WinApi.keybd_event(Keys.CapsLock, 0, 0, 0); //WinApi.keybd_event(Keys.CapsLock, 0, WinApi.KEYEVENTF_KEYUP, 0); //WinApi.keybd_event(Keys.E, 0, 0, 0); //WinApi.keybd_event(Keys.E, 0, WinApi.KEYEVENTF_KEYUP, 0); //Thread.Sleep(10); //WinApi.keybd_event(Keys.S, 0, 0, 0); //WinApi.keybd_event(Keys.S, 0, WinApi.KEYEVENTF_KEYUP, 0); //Thread.Sleep(10); //WinApi.keybd_event(Keys.T, 0, 0, 0); //WinApi.keybd_event(Keys.T, 0, WinApi.KEYEVENTF_KEYUP, 0); //Thread.Sleep(10); #endregion //获取 UI-Automation 元素 值 ValuePattern vpTextBox1 = (ValuePattern)Edititem.GetCurrentPattern(ValuePattern.Pattern); string valStr = vpTextBox1.Current.Value; //vpTextBox1.SetValue(valStr); //SendKeys sendkeys =new SendKeys(); //List<string> keys = new List<string>(); //keys.Add(sendkeys.Ctrl); //keys.Add(sendkeys.Enter); //sendkeys.Sendkeys(Edititem, keys.ToArray()); if (tabCtrlMessage.TabPages.ContainsKey(WindowHandle.ToString())) { int tbpageNum = tabCtrlMessage.TabPages.IndexOfKey(WindowHandle.ToString()); ListView lstv = new ListView(); if (tabCtrlMessage.TabPages[tbpageNum].Controls[0] is ListView) { lstv = (ListView)tabCtrlMessage.TabPages[tbpageNum].Controls[0]; var StrLines = valStr.Split('\r'); foreach (var Stritem in StrLines) { ListViewItem lstitem = new ListViewItem(Edititem.Current.Name + ":" + Stritem); lstv.Items.Add(lstitem); } } else { tabCtrlMessage.TabPages[tbpageNum].Controls.Clear(); var StrLines = valStr.Split('\r'); foreach (var Stritem in StrLines) { ListViewItem lstitem = new ListViewItem(Edititem.Current.Name + ":" + Stritem); lstv.Items.Add(lstitem); } lstv.Width = tabCtrlMessage.Width; lstv.Height = tabCtrlMessage.Height; lstv.DrawItem += lstv_DrawItem; tabCtrlMessage.TabPages[tabCtrlMessage.TabPages.Count - 1].Controls.Add(lstv); } } else { tabCtrlMessage.TabPages.Add(WindowHandle.ToString(), Name); ListView lstv = new ListView(); lstv.Width = tabCtrlMessage.Width; lstv.Height = tabCtrlMessage.Height; var StrLines = valStr.Split('\r'); foreach (var Stritem in StrLines) { ListViewItem lstitem = new ListViewItem(Edititem.Current.Name + ":" + Stritem); lstv.Items.Add(lstitem); } lstv.DrawItem += lstv_DrawItem; tabCtrlMessage.TabPages[tabCtrlMessage.TabPages.Count - 1].Controls.Add(lstv); } } } } else { } } } }
/// <summary> /// 登陆 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void btnLogin_Click(object sender, EventArgs e) { //根目录 AutomationElement aeDeskTop = AutomationElement.RootElement; //所有 QQ相关的窗口 var AllChildrenElement = aeDeskTop.FindAll(TreeScope.Descendants, new PropertyCondition(AutomationElement.ClassNameProperty, "TXGuiFoundation")); foreach (AutomationElement item in AllChildrenElement) { int WindowHandle = item.Current.NativeWindowHandle; string Name = item.Current.Name; if (!string.IsNullOrEmpty(Name)) { if (Name == "QQ") { AutomationElementCollection AutoEleCll = item.FindAll(TreeScope.Children, Condition.TrueCondition); if (AutoEleCll.Count > 0) { if (AutoEleCll.Count > 3) { //已登陆的QQ } else { #region QQ登陆框 //激活聊天主窗体 WinApi.ShowWindow(new IntPtr(WindowHandle), 1); WinApi.SetActiveWindow(new IntPtr(WindowHandle)); WinApi.SetForegroundWindow(new IntPtr(WindowHandle)); IntPtr QQpswIntPtr = WinApi.FindWindow("TXGuiFoundation", "QQ"); if (QQpswIntPtr != IntPtr.Zero) { IntPtr PswEditIntPtr = WinApi.FindWindowEx(QQpswIntPtr, IntPtr.Zero, "Edit", "QQEdit"); if (PswEditIntPtr != IntPtr.Zero) { WinApi.SendMessage(PswEditIntPtr, WinApi.EM_SETSEL, -1, -1);// WinApi.SendMessage(PswEditIntPtr, WinApi.WM_SETTEXT, 0, "~foreverhot1019~"); } } AndCondition pcTarget = null; pcTarget = new AndCondition( new PropertyCondition(AutomationElement.NameProperty, "密码"), new PropertyCondition(AutomationElement.ControlTypeProperty, ControlType.Pane)); AutomationElementCollection _AutoEleCll = item.FindAll(TreeScope.Descendants, pcTarget); if (_AutoEleCll.Count > 0) { foreach (AutomationElement Passworditem in _AutoEleCll) { //激活聊天主窗体 WinApi.ShowWindow(new IntPtr(WindowHandle), 1); WinApi.SetActiveWindow(new IntPtr(WindowHandle)); WinApi.SetForegroundWindow(new IntPtr(WindowHandle)); //整个 密码pane 框的位置 System.Windows.Rect rect = Passworditem.Current.BoundingRectangle; AndCondition _pcTarget = new AndCondition( new PropertyCondition(AutomationElement.IsEnabledProperty, true), new PropertyCondition(AutomationElement.IsPasswordProperty, false), new PropertyCondition(AutomationElement.ControlTypeProperty, ControlType.Pane)); AutomationElementCollection pswPaneElementCollection = Passworditem.FindAll(TreeScope.Descendants, _pcTarget); if (pswPaneElementCollection.Count > 0) { foreach (AutomationElement pswitem in _AutoEleCll) { AutomationElementCollection _pswitemcoll = pswitem.FindAll(TreeScope.Children, Condition.TrueCondition); if (_pswitemcoll.Count <= 0) { rect = pswitem.Current.BoundingRectangle; } } } //元素 左上角位置 System.Drawing.Point tPoint = new System.Drawing.Point(); tPoint.X = Convert.ToInt32(rect.Left); tPoint.Y = Convert.ToInt32(rect.Top); //元素正中间位置 System.Drawing.Point CenterPoint = new System.Drawing.Point(); CenterPoint.X = Convert.ToInt32(rect.Left + rect.Width / 2); CenterPoint.Y = Convert.ToInt32(rect.Top + rect.Height / 2); //设置鼠标到指定位置 WinApi.SetCursorPos(CenterPoint); //模拟鼠标点击 WinApi.mouse_event(WinApi.MOUSEEVENTF_LEFTDOWN | WinApi.MOUSEEVENTF_LEFTUP, 0, 0, 0, 0); Thread.Sleep(10); //设置窗体内容(模拟键盘事件 消息方式) WinApi.keybd_event(Keys.ShiftKey, 0, 0, 0); WinApi.keybd_event(192, 0, 0, 0); WinApi.keybd_event(192, 0, WinApi.KEYEVENTF_KEYUP, 0); WinApi.keybd_event(Keys.ShiftKey, 0, WinApi.KEYEVENTF_KEYUP, 0); Thread.Sleep(10); WinApi.keybd_event(Keys.F, 0, 0, 0); WinApi.keybd_event(Keys.F, 0, WinApi.KEYEVENTF_KEYUP, 0); WinApi.keybd_event(Keys.O, 0, 0, 0); WinApi.keybd_event(Keys.O, 0, WinApi.KEYEVENTF_KEYUP, 0); WinApi.keybd_event(Keys.R, 0, 0, 0); WinApi.keybd_event(Keys.R, 0, WinApi.KEYEVENTF_KEYUP, 0); WinApi.keybd_event(Keys.E, 0, 0, 0); WinApi.keybd_event(Keys.E, 0, WinApi.KEYEVENTF_KEYUP, 0); WinApi.keybd_event(Keys.V, 0, 0, 0); WinApi.keybd_event(Keys.V, 0, WinApi.KEYEVENTF_KEYUP, 0); WinApi.keybd_event(Keys.E, 0, 0, 0); WinApi.keybd_event(Keys.E, 0, WinApi.KEYEVENTF_KEYUP, 0); WinApi.keybd_event(Keys.R, 0, 0, 0); WinApi.keybd_event(Keys.R, 0, WinApi.KEYEVENTF_KEYUP, 0); WinApi.keybd_event(Keys.H, 0, 0, 0); WinApi.keybd_event(Keys.H, 0, WinApi.KEYEVENTF_KEYUP, 0); WinApi.keybd_event(Keys.O, 0, 0, 0); WinApi.keybd_event(Keys.O, 0, WinApi.KEYEVENTF_KEYUP, 0); WinApi.keybd_event(Keys.T, 0, 0, 0); WinApi.keybd_event(Keys.T, 0, WinApi.KEYEVENTF_KEYUP, 0); WinApi.keybd_event(Keys.D1, 0, 0, 0); WinApi.keybd_event(Keys.D1, 0, WinApi.KEYEVENTF_KEYUP, 0); WinApi.keybd_event(Keys.D0, 0, 0, 0); WinApi.keybd_event(Keys.D0, 0, WinApi.KEYEVENTF_KEYUP, 0); WinApi.keybd_event(Keys.D1, 0, 0, 0); WinApi.keybd_event(Keys.D1, 0, WinApi.KEYEVENTF_KEYUP, 0); WinApi.keybd_event(Keys.D9, 0, 0, 0); WinApi.keybd_event(Keys.D9, 0, WinApi.KEYEVENTF_KEYUP, 0); Thread.Sleep(10); AndCondition __pcTarget = new AndCondition( new PropertyCondition(AutomationElement.NameProperty, "登 录"), new PropertyCondition(AutomationElement.ControlTypeProperty, ControlType.Button)); AutomationElementCollection __AutoEleCll = item.FindAll(TreeScope.Descendants, __pcTarget); if (__AutoEleCll.Count > 0) { foreach (AutomationElement Loginitem in __AutoEleCll) { //登陆框的位置 System.Windows.Rect LoginRect = Loginitem.Current.BoundingRectangle; //元素 左上角位置 System.Drawing.Point _tPoint = new System.Drawing.Point(); _tPoint.X = Convert.ToInt32(LoginRect.Left); _tPoint.Y = Convert.ToInt32(LoginRect.Top); //元素正中间位置 System.Drawing.Point _CenterPoint = new System.Drawing.Point(); _CenterPoint.X = Convert.ToInt32(LoginRect.Left + LoginRect.Width / 2); _CenterPoint.Y = Convert.ToInt32(LoginRect.Top + LoginRect.Height / 2); //设置鼠标到指定位置 WinApi.SetCursorPos(_CenterPoint); //模拟鼠标点击 WinApi.mouse_event(WinApi.MOUSEEVENTF_LEFTDOWN | WinApi.MOUSEEVENTF_LEFTUP, 0, 0, 0, 0); } } } } #endregion } } } } } }
public List <T> GetObjectsInRegion <T>(int lenght = DefaultQueryProximityLenght) where T : WorldObject { var proximityRectangle = new Rect(this.Position.x - lenght / 2, this.Position.y - lenght / 2, lenght, lenght); return(this.World.QuadTree.Query <T>(proximityRectangle)); }
public RectangleElement(WPF.Rect rect, WPF.Media.Color color) : this(rect.TopLeft, rect.BottomRight, color) { }
/// <summary> /// Performs layout of labels. /// </summary> /// <param name="labels"></param> /// <param name="rectangles"></param> /// <param name="border"></param> public override void Arrange(IList <ILabel> labels, IList <Rect> rectangles, System.Windows.Rect border) { // copy original labels to the temporary working set var state = CreateState(labels); // find the distance from border int cnt = labels.Count; // sort according to the distance // the labels which are closer to the border have less freedom LabelState[] array = state.ToArray <LabelState>(); // main positioning cycle for (int i = 0; i < cnt; i++) { var lbl = array[i]; if (lbl.IsVisible) { bool good = false; // first try to put label closely to anchor point // the anchor is on the label corner(4 possible states) #if (false) for (int pos = 0; pos < 4; pos++) { SetPosition(lbl, (LabelPosition)pos); good = IsGoodPosition(lbl, border, array, rectangles, i); if (good) { break; } } #endif // next if (!good) { // try to increase offset for (double offset = offset_start; offset < max_offset; offset += offset_step) { // and different angles var angle = 180.0 / Math.PI * Math.Atan2(lbl.Point.Y - lbl.PlotCenter.Y, lbl.Point.X - lbl.PlotCenter.X); var angles = new double[] { angle, angle - 10, angle + 10, angle - 20, angle + 20, }; for (int ia = 0; ia < angles.Length; ia++) { SetPosition(lbl, angles[ia], offset); good = IsGoodPosition(lbl, border, array, rectangles, i); if (good) { break; } } if (good) { break; } } } } } // position real labels for (int i = 0; i < cnt; i++) { state[i].CopyState(labels[i]); } }
public void SetCustomLabelSize(SysRect rect) { EdgeLabelControl.SetSize(rect); }
public void SetClipReplace(RectangleF rect) { PointOutside.Check(ref rect); FCanvas.SetClip(rect, System.Drawing.Drawing2D.CombineMode.Replace); }
private void DoRender(IntPtr pIDXGISurface, bool dunnoWhatThisIsFor) { if (pIDXGISurface != m_pIDXGISurfacePreviousNoRef) { m_pIDXGISurfacePreviousNoRef = pIDXGISurface; // Create the render target Surface dxgiSurface = new Surface(pIDXGISurface); SurfaceDescription sd = dxgiSurface.Description; RenderTargetProperties rtp = new RenderTargetProperties( RenderTargetType.Default, new PixelFormat(Format.Unknown, SharpDX.Direct2D1.AlphaMode.Premultiplied), 96, 96, // Force bitmap rendering if you want it to work on remote desktop connections RenderTargetUsage.None, FeatureLevel.Level_DEFAULT); try { _renderTarget = new RenderTarget(_d2dFactory, dxgiSurface, rtp); } catch (Exception) { return; } // Clear the surface to transparent //_renderTarget.BeginDraw(); //_renderTarget.Clear(new ColorF(1, 1, 1, 0)); //_renderTarget.EndDraw(); _isValid = true; } if (PrimitiveTransform == null || PrimitiveList == null) { return; } _renderTarget.BeginDraw(); _renderTarget.Clear(new SharpDX.Mathematics.Interop.RawColor4(1, 1, 1, 0)); foreach (IChartRendererD2D primitive in PrimitiveList) { primitive.RenderFilledElements(this, ChartDataRange, PrimitiveTransform); } foreach (IChartRendererD2D primitive in PrimitiveList) { primitive.RenderUnfilledElements(this, ChartDataRange, PrimitiveTransform); } // Now render the points System.Windows.Rect bounds = new System.Windows.Rect(-3, -3, _canvasRect.Width + 6, _canvasRect.Height + 6); foreach (ChartPrimitive primitive in PrimitiveList) { if (primitive.ShowPoints) { var brush = new SolidColorBrush(RenderTarget, primitive.PointColor.ToD2D()); Ellipse ellipse = new Ellipse(new SharpDX.Mathematics.Interop.RawVector2(0, 0), 2, 2); foreach (Point point in primitive.Points) { Point transformedPoint = PrimitiveTransform.Transform(point); if (bounds.Contains(transformedPoint)) { ellipse.Point = transformedPoint.ToD2D(); RenderTarget.DrawEllipse(ellipse, brush, 1); } } } } _renderTarget.EndDraw(); }
public void DrawImage(Image image, RectangleF destRect, RectangleF srcRect, long transparentColor, int brightness, int contrast, int gamma, Color shadowColor, Stream imgData) { if (PointOutside.Check(ref srcRect)) { return; } if (PointOutside.Check(ref destRect)) { return; } if (image.Height <= 0 || image.Width <= 0) { return; } bool ChangedParams = brightness != FlxConsts.DefaultBrightness || contrast != FlxConsts.DefaultContrast || gamma != FlxConsts.DefaultGamma || shadowColor != Colors.Transparent; ImageAttributes imgAtt = null; try { if (transparentColor != FlxConsts.NoTransparentColor) { long cl = transparentColor; Color tcl = ColorUtil.FromArgb(0xFF, (byte)(cl & 0xFF), (byte)((cl & 0xFF00) >> 8), (byte)((cl & 0xFF0000) >> 16)); imgAtt = new ImageAttributes(); imgAtt.SetColorKey(tcl, tcl); } if (gamma != FlxConsts.DefaultGamma) { if (imgAtt == null) { imgAtt = new ImageAttributes(); } imgAtt.SetGamma((real)((UInt32)gamma) / 65536f); } if (!ChangedParams && srcRect.Top == 0 && srcRect.Left == 0 && srcRect.Width == image.Width && srcRect.Height == image.Height && imgAtt == null) { FCanvas.DrawImage(image, destRect); } else { Image FinalImage = image; try { if (image.RawFormat.Equals(ImageFormat.Wmf) || image.RawFormat.Equals(ImageFormat.Emf)) { FinalImage = FlgConsts.RasterizeWMF(image); //metafiles do not like cropping or changing attributes. } if (ChangedParams) { if (shadowColor != ColorUtil.Empty) { FlgConsts.MakeImageGray(ref imgAtt, shadowColor); } else { FlgConsts.AdjustImage(ref imgAtt, brightness, contrast); } } PointF[] ImageRect = new PointF[] { new PointF(destRect.Left, destRect.Top), new PointF(destRect.Right, destRect.Top), new PointF(destRect.Left, destRect.Bottom) }; FCanvas.DrawImage(FinalImage, ImageRect, srcRect, GraphicsUnit.Pixel, imgAtt); } finally { if (FinalImage != image) { FinalImage.Dispose(); } } } } finally { if (imgAtt != null) { imgAtt.Dispose(); } } }
public override void InvalidateVisual(System.Windows.Rect canvasRect) { _interopImage.SetPixelSize((uint)canvasRect.Width, (uint)canvasRect.Height); _canvasRect = canvasRect; _interopImage.RequestRender(); }
protected override void OnStartup(StartupEventArgs e) { Current.DispatcherUnhandledException += OnDispatcherUnhandledException; base.OnStartup(e); if (!SingleInstance <App> .InitializeAsFirstInstance(PhoenixUniqueKey)) { Current.Shutdown(); return; } OriginResolution = new Rect { Width = SystemParameters.VirtualScreenWidth, Height = SystemParameters.VirtualScreenHeight }; if (Settings.Default.ResetPennding) { Settings.Default.Reset(); } if (Settings.Default.ModeIndex == -1) { Utils.UpdateScreenResolution(); } if (string.IsNullOrEmpty(Settings.Default.BackupPath)) { var executionPath = AppDomain.CurrentDomain.BaseDirectory; var backupPath = string.Format(@"{0}Backup", executionPath); Settings.Default.BackupPath = backupPath; Settings.Default.Save(); } if (!Directory.Exists(Settings.Default.BackupPath)) { Directory.CreateDirectory(Settings.Default.BackupPath, new DirectorySecurity(AppDomain.CurrentDomain.BaseDirectory, AccessControlSections.Owner)); } Utils.SetResolution(); Utils.EnsureCulture(); Utils.AddThemeBaseDictionaries(); try { DbContext.Init(); } catch (Exception ex) { Logger.Write(ex); MessageWindowHelpers.Show(null, SplashResources.DatabaseInitFailed, MessageBoxButton.OK, MessageBoxImage.Hand); Current.Shutdown(); return; } try { PropsService.Get(Guid.NewGuid()); } catch (Exception ex) { Logger.Write(ex); MessageWindowHelpers.Show(null, SplashResources.DatabaseTestFailed, MessageBoxButton.OK, MessageBoxImage.Hand); Current.Shutdown(); return; } try { var administratorRole = RolesService.Instanse.GetAdministrator(false); if (administratorRole == null) { RolesService.Instanse.CreateAdministrator(); } var systemUser = UsersService.Instanse.GetSystemUser(false); if (systemUser == null) { UsersService.Instanse.CreateSystemUser(); } } catch (Exception exception) { Logger.Write(exception); MessageWindowHelpers.Show(null, SplashResources.TestCheckIndeedRecordsFailed, MessageBoxButton.OK, MessageBoxImage.Hand); } }
public PlotRendererD2D() { _interopImage = new D2DD3DImage(); _interopImage.SetPixelSize(100, 100); _canvasRect = new System.Windows.Rect(0, 0, 100, 100); }
Win.Rect Transform(Win.Rect rect, Tuple <Win.Vector, Win.Point> transform) { return(new Win.Rect(Transform(rect.BottomLeft, transform), Transform(rect.TopRight, transform))); }
protected override void ArrangeCore(Rect finalRect) { //var internalSize = finalRect.Size; //internalSize.Width -= (InternalMargin.Right + InternalMargin.Left); //internalSize.Height -= (InternalMargin.Bottom + InternalMargin.Top); foreach (inkControl child in Children) { if (child.Visibility == Visibility.Collapsed) { continue; } var width = child.DesiredSize.Width; var height = child.DesiredSize.Height; double x = 0, y = 0; switch (child.Widget.Layout.HAlign.Value) { case Enums.inkEHorizontalAlign.Fill: x = child.Margin.Left; break; case Enums.inkEHorizontalAlign.Left: x = child.Margin.Left; break; case Enums.inkEHorizontalAlign.Right: x = finalRect.Size.Width - width - child.Margin.Right; break; case Enums.inkEHorizontalAlign.Center: x = (finalRect.Size.Width - width) / 2 + child.Margin.Left - child.Margin.Right; break; } switch (child.Widget.Layout.VAlign.Value) { case Enums.inkEVerticalAlign.Fill: y = child.Margin.Top; break; case Enums.inkEVerticalAlign.Top: y = child.Margin.Top; break; case Enums.inkEVerticalAlign.Bottom: y = finalRect.Size.Height - height - child.Margin.Bottom; break; case Enums.inkEVerticalAlign.Center: y = (finalRect.Size.Height - height) / 2 + child.Margin.Top - child.Margin.Bottom; break; } //x += InternalMargin.Left; //y += InternalMargin.Top; child.Arrange(new Rect(x, y, width, height)); } base.ArrangeCore(finalRect); }
public Bitmap Shadow(Bitmap src, Color color, int width, double opacity = 0.6f, double angle = 315) { Bitmap result = new Bitmap(src); #region Get DPI float dpiX = 96f; float dpiY = 96f; using (Graphics g = Graphics.FromHwnd(IntPtr.Zero)) { dpiX = g.DpiX; dpiY = g.DpiY; } #endregion int offset = 4 * width; #region Create Effect var effect = new Media.Effects.DropShadowEffect(); effect.BlurRadius = width; effect.Color = color.ToMediaColor(); effect.Direction = angle; effect.Opacity = opacity; effect.ShadowDepth = width; //var effect = new Media.Effects.BlurEffect(); //effect.Radius = 50; #endregion #region Draw source bitmap to DrawingVisual Media.DrawingVisual drawingVisual = new Media.DrawingVisual(); drawingVisual.Effect = effect; using (var drawingContext = drawingVisual.RenderOpen()) { System.Windows.Rect dRect = new System.Windows.Rect(2 * width, 2 * width, src.Width, src.Height); drawingContext.DrawImage(src.ToBitmapSource(), dRect); drawingContext.Close(); } #endregion #region Render the DrawingVisual into a RenderTargetBitmap var rtb = new Media.Imaging.RenderTargetBitmap( src.Width + offset, src.Height + offset, dpiX, dpiY, Media.PixelFormats.Pbgra32); rtb.Render(drawingVisual); #endregion #region Create a System.Drawing.Bitmap var bitmap = new Bitmap(rtb.PixelWidth, rtb.PixelHeight, PixelFormat.Format32bppArgb); #endregion #region Copy the RenderTargetBitmap pixels into the bitmap's pixel buffer var pdata = bitmap.LockBits( new Rectangle(0, 0, bitmap.Width, bitmap.Height), ImageLockMode.WriteOnly, bitmap.PixelFormat); rtb.CopyPixels(System.Windows.Int32Rect.Empty, pdata.Scan0, pdata.Stride * pdata.Height, pdata.Stride); bitmap.UnlockBits(pdata); #endregion #region Crop Transparent Area var rect = bitmap.ContentBound(); result = new Bitmap(rect.Width, rect.Height, bitmap.PixelFormat); using (var g = Graphics.FromImage(result)) { g.DrawImage(bitmap, 0, 0, rect, GraphicsUnit.Pixel); } #endregion return(result); }
public Bitmap Shader(Bitmap src, double radius = 10) { Bitmap result = new Bitmap(src); #region Get DPI float dpiX = 96f; float dpiY = 96f; using (Graphics g = Graphics.FromHwnd(IntPtr.Zero)) { dpiX = g.DpiX; dpiY = g.DpiY; } #endregion int width = (int)Math.Ceiling(radius); int offset = 4 * width; #region Create Effect var effect = new MyShaderEffect(); //Media.Effects.ShaderRenderMode = Media.Effects.ShaderRenderMode.Auto; //effect. #endregion #region Draw source bitmap to DrawingVisual Media.DrawingVisual drawingVisual = new Media.DrawingVisual(); drawingVisual.Effect = effect; using (var drawingContext = drawingVisual.RenderOpen()) { //drawingContext.PushEffect( new Media.Effects.BlurBitmapEffect(), null ); System.Windows.Rect dRect = new System.Windows.Rect(2 * width, 2 * width, src.Width, src.Height); drawingContext.DrawImage(src.ToBitmapSource(), dRect); drawingContext.Close(); } #endregion #region Render the DrawingVisual into a RenderTargetBitmap var rtb = new Media.Imaging.RenderTargetBitmap( src.Width + offset, src.Height * offset, dpiX, dpiY, Media.PixelFormats.Pbgra32); rtb.Render(drawingVisual); #endregion #region Create a System.Drawing.Bitmap var bitmap = new Bitmap(rtb.PixelWidth, rtb.PixelHeight, PixelFormat.Format32bppArgb); #endregion #region Copy the RenderTargetBitmap pixels into the bitmap's pixel buffer var pdata = bitmap.LockBits( new Rectangle(0, 0, bitmap.Width, bitmap.Height), ImageLockMode.WriteOnly, bitmap.PixelFormat); rtb.CopyPixels(System.Windows.Int32Rect.Empty, pdata.Scan0, pdata.Stride * pdata.Height, pdata.Stride); bitmap.UnlockBits(pdata); #endregion #region Crop Opaque var rect = bitmap.ContentBound(); rect.Width = rect.Width < 0 ? 1 : rect.Width + 2; rect.Height = rect.Height < 0 ? 1 : rect.Height + 2; result = new Bitmap(rect.Width, rect.Height, bitmap.PixelFormat); using (var g = Graphics.FromImage(result)) { g.DrawImage(bitmap, 0, 0, rect, GraphicsUnit.Pixel); } #endregion return(result); }