private void mapView_MouseDown(object sender, MouseButtonEventArgs e) { try { graphicsLayer.Graphics.Clear(); // Convert screen point to map point var point = mapView.ScreenToLocation(e.GetPosition(mapView)); var buffer = GeometryEngine.Buffer(point, 5 * MILES_TO_METERS); //show geometries on map if (graphicsLayer != null) { var pointGraphic = new Graphic { Geometry = point, Symbol = _pinSymbol }; graphicsLayer.Graphics.Add(pointGraphic); var bufferGraphic = new Graphic { Geometry = buffer, Symbol = _bufferSymbol }; graphicsLayer.Graphics.Add(bufferGraphic); } } catch (Exception ex) { MessageBox.Show(ex.Message, "Geometry Engine Failed!"); } }
private async void mapView1_MapViewTapped(object sender, Esri.ArcGISRuntime.Controls.MapViewInputEventArgs e) { var graphicsLayer = mapView1.Map.Layers["MyGraphicsLayer"] as GraphicsLayer; var editGraphicsLayer = mapView1.Map.Layers["EditGraphicsLayer"] as GraphicsLayer; if (graphicBeingEdited == null) { var hit = await graphicsLayer.HitTestAsync(sender as Esri.ArcGISRuntime.Controls.ViewBase, e.Position); if (hit != null) { graphicBeingEdited = hit; //highlight the active graphic graphicBeingEdited.IsSelected = true; //Create a temporary we can move around without 'disturbing' the original feature until commit Graphic g = new Graphic(); g.Symbol = hit.Symbol ?? graphicsLayer.Renderer.GetSymbol(hit); g.Geometry = hit.Geometry; editGraphicsLayer.Graphics.Add(g); } } else //Commit and clean up { graphicBeingEdited.Geometry = e.Location; graphicBeingEdited.IsSelected = false; graphicBeingEdited = null; editGraphicsLayer.Graphics.Clear(); } }
private async Task SelectParcelForOffsetAsync() { try { ResetButton.IsEnabled = false; _offsetOverlay.Graphics.Clear(); var pointGeom = await MyMapView.Editor.RequestPointAsync(); var screenPnt = MyMapView.LocationToScreen(pointGeom); _selectedParcelGraphic = await _parcelOverlay.HitTestAsync(MyMapView, screenPnt); DoOffset(); } catch (TaskCanceledException) { } catch (Exception ex) { MessageBox.Show(ex.Message, "Sample Error"); } finally { ResetButton.IsEnabled = true; } }
private async Task DoGeodesicLength() { ResetButton.IsEnabled = false; try { if (mapView1.Editor.IsActive) mapView1.Editor.Cancel.Execute(null); //Get the input polygon geometry from the user inputGeom = await mapView1.Editor.RequestShapeAsync(DrawShape.Polyline); if (inputGeom != null) { //Add the polygon drawn by the user var g = new Graphic { Geometry = inputGeom, }; myGraphicsLayer.Graphics.Add(g); //Get the label point for the input geometry var length = GeometryEngine.GeodesicLength(inputGeom); LineLengthTextBlock.Text = length.ToString("N2") + " m"; LineLengthTextBlock.Visibility = Windows.UI.Xaml.Visibility.Visible; } } catch (Exception) { } ResetButton.IsEnabled = true; }
private void AddPolyLineGraphics() { MapPoint ptStart = (MapPoint)graphicsLayer.Graphics[0].Geometry; MapPoint ptEnd = (MapPoint)graphicsLayer.Graphics[5].Geometry; // Solid Blue line above point graphics Graphic blueLine = new Graphic() { Symbol = new SimpleLineSymbol() { Color = Colors.Blue, Style = SimpleLineStyle.Solid, Width = 4 }, Geometry = new Polyline(new CoordinateCollection() { new Coordinate(ptStart.X, ptStart.Y + 1000000), new Coordinate(ptEnd.X, ptEnd.Y + 1000000) }) }; // Dashed Green line below point graphics Graphic greenLine = new Graphic() { Symbol = new SimpleLineSymbol() { Color = Colors.Green, Style = SimpleLineStyle.Dash, Width = 4 }, Geometry = new Polyline(new CoordinateCollection() { new Coordinate(ptStart.X, ptStart.Y - 1000000), new Coordinate(ptEnd.X, ptEnd.Y - 1000000) }) }; graphicsLayer.Graphics.Add(blueLine); graphicsLayer.Graphics.Add(greenLine); }
private async Task SelectParcelForOffset() { ResetButton.IsEnabled = false; try { offsetGraphicsLayer.Graphics.Clear(); var pointGeom = await mapView1.Editor.RequestPointAsync(); pointGeom.SpatialReference = mapView1.SpatialReference; var screenPnt = mapView1.LocationToScreen(pointGeom); selectedParcelGraphic = await parcelGraphicsLayer.HitTestAsync(mapView1, screenPnt); DoOffset(); } catch (Exception) { } ResetButton.IsEnabled = true; }
// Unions feature geometries with a user defined polygon. private async void UnionButton_Click(object sender, RoutedEventArgs e) { try { resultGraphics.Graphics.Clear(); // wait for user to draw a polygon var poly = await mapView.Editor.RequestShapeAsync(DrawShape.Polygon); // get intersecting features from the feature layer SpatialQueryFilter filter = new SpatialQueryFilter(); filter.Geometry = GeometryEngine.Project(poly, _statesLayer.FeatureTable.SpatialReference); filter.SpatialRelationship = SpatialRelationship.Intersects; filter.MaximumRows = 52; var stateFeatures = await _statesLayer.FeatureTable.QueryAsync(filter); // Union the feature geometries and add to graphics layer var states = stateFeatures.Select(feature => feature.Geometry); var sourcePolys = states.ToList(); var unionPoly = GeometryEngine.Union(sourcePolys); var unionGraphic = new Graphic(unionPoly, _fillSymbol); resultGraphics.Graphics.Add(unionGraphic); } catch (Exception ex) { MessageBox.Show("Union Error: " + ex.Message, "Union Sample"); } }
private void CreateOverlay() { // Create polygon builder and add polygon corners into it PolygonBuilder builder = new PolygonBuilder(SpatialReferences.WebMercator); builder.AddPoint(new MapPoint(-20e5, 20e5)); builder.AddPoint(new MapPoint(20e5, 20e5)); builder.AddPoint(new MapPoint(20e5, -20e5)); builder.AddPoint(new MapPoint(-20e5, -20e5)); // Get geometry from the builder Polygon polygonGeometry = builder.ToGeometry(); // Create symbol for the polygon SimpleFillSymbol polygonSymbol = new SimpleFillSymbol( SimpleFillSymbolStyle.Solid, System.Drawing.Color.Yellow, null); // Create new graphic Graphic polygonGraphic = new Graphic(polygonGeometry, polygonSymbol); // Create overlay to where graphics are shown _polygonOverlay = new GraphicsOverlay(); _polygonOverlay.Graphics.Add(polygonGraphic); // Add created overlay to the MapView _myMapView.GraphicsOverlays.Add(_polygonOverlay); }
static GasOverlayMats() { TransmitterShader = ShaderDatabase.MetaOverlay; Graphic subGraphic = GraphicDatabase.Get<Graphic_Single>(TransmitterAtlasPath, TransmitterShader); LinkedOverlayGraphic = new Graphic_LinkedGasPipe(subGraphic); subGraphic.MatSingle.renderQueue = 3800; }
private void MyMapView_MouseMove(object sender, MouseEventArgs e) { try { // Convert screen point to map point var point = MyMapView.ScreenToLocation(e.GetPosition(MyMapView)); if (point == null) return; var buffer = GeometryEngine.GeodesicBuffer( GeometryEngine.NormalizeCentralMeridian(point), //Normalize in case we we're too far west/east of the world bounds 500, LinearUnits.Miles); Graphic bufferGraphic = null; if (_graphicsOverlay.Graphics.Count == 0) { bufferGraphic = new Graphic { Geometry = buffer, Symbol = _bufferSymbol }; _graphicsOverlay.Graphics.Add(bufferGraphic); } else bufferGraphic = _graphicsOverlay.Graphics[0]; bufferGraphic.Geometry = buffer; } catch (Exception ex) { MessageBox.Show(ex.Message, "Geometry Engine Failed!"); } }
private void ParseFile(string cached) { string[] sReferences = File.ReadAllLines(cached); foreach (string ap in sReferences) { try { string[] s = ap.Split(','); var g = new Graphic(); var pd = new ResourceDictionary(); pd.Source = new Uri("csGeoLayers;component/csGeoLayers/FlightTracker/FTDictionary.xaml", UriKind.Relative); g.Symbol = pd["MediumMarkerSymbol"] as SimpleMarkerSymbol; var mp = new MapPoint((float) Convert.ToDouble(s[7], CultureInfo.InvariantCulture), (float) Convert.ToDouble(s[6], CultureInfo.InvariantCulture), new SpatialReference(4326)); g.Geometry = mp; Graphics.Add(g); } catch (Exception) { } } AppStateSettings.Instance.FinishDownload(_id); }
public void OnPending(Graphic parent) { this.parent = parent as BodyGraphic; logic = new RaySegmentsCollisionLogic(this.parent.Body); parent.Parent.physicsLogics.Add(logic); logic.NewInfo += logic_NewInfo; }
private IEnumerator WaitForFade(Graphic g, float fadeInTime, float waitTime, float fadeOutTime, float waitAfter = 0) { yield return g.DOFade(1, fadeInTime).WaitForCompletion(); yield return StartCoroutine(WaitOrSkip(waitTime)); yield return g.DOFade(0, fadeOutTime).WaitForCompletion(); yield return StartCoroutine(WaitOrSkip(waitAfter)); }
public void SpawnSetup() { uiOverlay = new DroidUIOverlay(parent); parent.drawer.renderer.graphics.ResolveGraphics(); parent.story.hairDef = DefDatabase<HairDef>.GetNamed("Shaved", true); try { if (headGraphicDef != null && bodyGraphicDef.supportsHead) { headGraphic = headGraphicDef.graphicData.Graphic; } } catch (Exception ex) { Log.Error(ex.ToString()); return; } try { bodyGraphic = bodyGraphicDef.graphicData.Graphic; } catch (Exception ex) { Log.Error(ex.ToString()); } if (headGraphic != null) { parent.drawer.renderer.graphics.headGraphic = this.headGraphic; parent.drawer.renderer.graphics.hairGraphic = GraphicDatabase.Get<Graphic_Multi>(parent.story.hairDef.texPath, ShaderDatabase.Cutout, Vector2.one, parent.story.hairColor); } parent.drawer.renderer.graphics.nakedGraphic = this.bodyGraphic; }
private void Initialize() { // Create new Map with basemap Map myMap = new Map(Basemap.CreateImagery()); // Create initial map location and reuse the location for graphic MapPoint centralLocation = new MapPoint(-226773, 6550477, SpatialReferences.WebMercator); Viewpoint initialViewpoint = new Viewpoint(centralLocation, 7500); // Set initial viewpoint myMap.InitialViewpoint = initialViewpoint; // Provide used Map to the MapView _myMapView.Map = myMap; // Create overlay to where graphics are shown GraphicsOverlay overlay = new GraphicsOverlay(); // Add created overlay to the MapView _myMapView.GraphicsOverlays.Add(overlay); // Create a simple marker symbol SimpleMarkerSymbol simpleSymbol = new SimpleMarkerSymbol() { Color = Color.Red, Size = 10, Style = SimpleMarkerSymbolStyle.Circle }; // Add a new graphic with a central point that was created earlier Graphic graphicWithSymbol = new Graphic(centralLocation, simpleSymbol); overlay.Graphics.Add(graphicWithSymbol); }
private void MyDrawObject_DrawComplete(object sender, DrawEventArgs args) { args.Geometry.SpatialReference = MyMap.SpatialReference; Graphic graphic = new Graphic(){ Geometry = args.Geometry }; if (args.Geometry is Polyline) graphic.Symbol = LayoutRoot.Resources["DefaultLineSymbol"] as ESRI.ArcGIS.Client.Symbols.Symbol; else graphic.Symbol = LayoutRoot.Resources["DefaultMarkerSymbol"] as ESRI.ArcGIS.Client.Symbols.Symbol; graphicsLayer.Graphics.Add(graphic); if (graphicsLayer.Graphics.Count == 1) MyDrawObject.DrawMode = DrawMode.Point; else if (graphicsLayer.Graphics.Count == 2) { MyDrawObject.IsEnabled = false; GeometryService geometryService = new GeometryService("http://tasks.arcgisonline.com/ArcGIS/rest/services/Geometry/GeometryServer"); geometryService.DistanceCompleted += GeometryService_DistanceCompleted; geometryService.Failed += GeometryService_Failed; MyDrawObject.DrawMode = DrawMode.Polyline; DistanceParameters distanceParameters = new DistanceParameters() { DistanceUnit = LinearUnit.SurveyMile, Geodesic = true }; geometryService.DistanceAsync(graphicsLayer.Graphics[0].Geometry, graphicsLayer.Graphics[1].Geometry,distanceParameters); ResponseTextBlock.Text = "The distance between geometries is... "; } }
private async void StartButton_Click(object sender, RoutedEventArgs e) { SetupUI(); // InstructionsTextBlock.Visibility = Windows.UI.Xaml.Visibility.Visible; StartButton.Visibility = Windows.UI.Xaml.Visibility.Collapsed; //Get the user's input densifyPolygonGeometry = (await MyMapView.Editor.RequestShapeAsync(DrawShape.Polygon)) as Polygon; //Create a graphic and add it to the PolygonGraphicsLayer var thePolygonGraphic = new Graphic { Geometry = densifyPolygonGeometry, Symbol = polygonSymbol }; graphicsLayerPolygon.Graphics.Add(thePolygonGraphic); //show the vertices for the polygon foreach (var vert in densifyPolygonGeometry.Parts.FirstOrDefault().GetPoints()) { var graphic = new Graphic { Geometry = new MapPoint(vert.X, vert.Y), Symbol = defaultVertexMarkerSymbol }; graphicsLayerVertices.Graphics.Add(graphic); } DensifyPolygonsButton.IsEnabled = true; }
// Unions feature geometries with a user defined polygon. private async void UnionButton_Click(object sender, RoutedEventArgs e) { try { _resultGraphics.Graphics.Clear(); // wait for user to draw a polygon var poly = await MyMapView.Editor.RequestShapeAsync(DrawShape.Polygon); // Take account of WrapAround var normalizedPoly = GeometryEngine.NormalizeCentralMeridian(poly) as Polygon; // get intersecting features from the feature layer SpatialQueryFilter filter = new SpatialQueryFilter(); filter.Geometry = GeometryEngine.Project(normalizedPoly, _statesLayer.FeatureTable.SpatialReference); filter.SpatialRelationship = SpatialRelationship.Intersects; filter.MaximumRows = 52; var stateFeatures = await _statesLayer.FeatureTable.QueryAsync(filter); // Union the geometries and add to graphics layer var states = stateFeatures.Select(feature => feature.Geometry); var unionPolys = states.ToList(); var unionPoly = GeometryEngine.Union(unionPolys); var unionGraphic = new Graphic(unionPoly, _fillSymbol); _resultGraphics.Graphics.Add(unionGraphic); } catch (Exception ex) { var _x = new MessageDialog("Union Error: " + ex.Message, "Sample Error").ShowAsync(); } }
void mapView1_MapViewTapped(object sender, MapViewInputEventArgs e) { graphicsLayer.Graphics.Clear(); try { var pointGeom = e.Location; var bufferGeom = GeometryEngine.Buffer(pointGeom, 5 * milesToMetersConversion); //show geometries on map if (graphicsLayer != null) { var pointGraphic = new Graphic { Geometry = pointGeom, Symbol = pms }; graphicsLayer.Graphics.Add(pointGraphic); var bufferGraphic = new Graphic { Geometry = bufferGeom, Symbol = sfs }; graphicsLayer.Graphics.Add(bufferGraphic); } } catch (Exception ex) { var dlg = new MessageDialog(ex.Message, "Geometry Engine Failed!"); var _ = dlg.ShowAsync(); } }
private void LocatorTask_AddressToLocationsCompleted(object sender, ESRI.ArcGIS.Client.Tasks.AddressToLocationsEventArgs args) { List<AddressCandidate> returnedCandidates = args.Results; AddressBorder.Visibility = System.Windows.Visibility.Collapsed; if (returnedCandidates.Count > 0) { AddressCandidate candidate = returnedCandidates[0]; Graphic graphic = new Graphic() { Symbol = LayoutRoot.Resources["DefaultMarkerSymbol"] as Symbol, Geometry = candidate.Location }; graphic.Attributes.Add("Address", candidate.Address); graphicsLayer.Graphics.Add(graphic); ResultsTextBlock.Visibility = System.Windows.Visibility.Visible; ResultsTextBlock.Text = candidate.Address; double displaySize = MyMap.MinimumResolution * 30; ESRI.ArcGIS.Client.Geometry.Envelope displayExtent = new ESRI.ArcGIS.Client.Geometry.Envelope( candidate.Location.X - (displaySize / 2), candidate.Location.Y - (displaySize / 2), candidate.Location.X + (displaySize / 2), candidate.Location.Y + (displaySize / 2)); MyMap.ZoomTo(displayExtent); } }
async void mapView1_Loaded(object sender, RoutedEventArgs e) { if (originalGraphicsLayer != null && originalGraphicsLayer.Graphics.Count == 0) { QueryTask queryTask = new QueryTask(new Uri("http://sampleserver1.arcgisonline.com/ArcGIS/rest/services/Specialty/ESRI_StatesCitiesRivers_USA/MapServer/1")); Query query = new Query("NAME = 'Mississippi'"); query.ReturnGeometry = true; query.OutSpatialReference = mapView1.SpatialReference; var results = await queryTask.ExecuteAsync(query, CancellationToken.None); foreach (Graphic g in results.FeatureSet.Features) { g.Symbol = defaultLineSymbol; g.Geometry.SpatialReference = mapView1.SpatialReference; originalGraphicsLayer.Graphics.Add(g); foreach (var pc in (g.Geometry as Polyline).Paths) { foreach (var point in pc) { var vertice = new Graphic() { Symbol = defaultMarkerSymbol, Geometry = new MapPoint(point.X, point.Y) }; originalGraphicsLayer.Graphics.Add(vertice); } } } GeneralizeButton.IsEnabled = true; } }
private async Task doCalculateAreaAndLength() { try { //Wait for user to draw var geom = await mapView1.Editor.RequestShapeAsync(DrawShape.Polygon); //show geometry on map graphicsLayer.Graphics.Clear(); var g = new Graphic { Geometry = geom, Symbol = LayoutRoot.Resources["DefaultFillSymbol"] as Esri.ArcGISRuntime.Symbology.Symbol }; graphicsLayer.Graphics.Add(g); //Calculate results var areaPlanar = GeometryEngine.Area(geom); ResultsAreaPlanar.Text = string.Format("{0} sq. miles", (areaPlanar * toSqMilesConversion).ToString("n3")); var perimPlanar = GeometryEngine.Length(geom); ResultsPerimeterPlanar.Text = string.Format("{0} miles", (perimPlanar * toMilesConversion).ToString("n3")); var areaGeodesic = GeometryEngine.GeodesicArea(geom); ResultsAreaGeodesic.Text = string.Format("{0} sq. miles", (areaGeodesic * toSqMilesConversion).ToString("n3")); var perimGeodesic = GeometryEngine.GeodesicLength(geom); ResultsPerimeterGeodesic.Text = string.Format("{0} miles", (perimGeodesic * toMilesConversion).ToString("n3")); Instructions.Visibility = Windows.UI.Xaml.Visibility.Collapsed; Results.Visibility = Windows.UI.Xaml.Visibility.Visible; } catch (System.Threading.Tasks.TaskCanceledException) { var dlg = new MessageDialog("Current sketch has been canceled.", "Task Canceled!"); var _ = dlg.ShowAsync(); } }
private async void MyMap_Tapped_1(object sender, Windows.UI.Xaml.Input.TappedRoutedEventArgs e) { var mp = MyMap.ScreenToMap(e.GetPosition(MyMap)); Graphic g = new Graphic() { Geometry = mp }; var graphicsLayer = MyMap.Layers["MyGraphicsLayer"] as GraphicsLayer; graphicsLayer.Graphics.Add(g); var bufferResult = GeometryEngine.Buffer(mp, 100); var bufferLayer = MyMap.Layers["BufferLayer"] as GraphicsLayer; bufferLayer.Graphics.Add(new Graphic() { Geometry = bufferResult }); var queryTask = new QueryTask(new Uri("http://sampleserver3.arcgisonline.com/ArcGIS/rest/services/BloomfieldHillsMichigan/Parcels/MapServer/2")); var query = new ESRI.ArcGIS.Runtime.Tasks.Query() { ReturnGeometry = true, OutSpatialReference = MyMap.SpatialReference, Geometry = bufferResult }; query.OutFields.Add("OWNERNME1"); try { var queryResult = await queryTask.ExecuteAsync(query); if (queryResult != null && queryResult.FeatureSet != null) { var resultLayer = MyMap.Layers["MyResultsGraphicsLayer"] as GraphicsLayer; resultLayer.Graphics.AddRange(queryResult.FeatureSet.Features); } } catch (Exception ex) { System.Diagnostics.Debug.WriteLine(ex.Message); } }
public override void Draw(Graphic g) { var position = _c.Position * _c.Scale; var size = _c.Size * _c.Scale; g.DrawRectangle(position, size, true, Style.Background); }
/// <summary> /// XAML creation of polygon and polyline geometries are currently not supported, so /// here they are created in code. Points are generated in the XAML for this sample. /// </summary> private void CreateGeometries() { var layer = mapView1.Map.Layers.OfType<GraphicsLayer>().First(); int i = 0; foreach (var g in layer.Graphics) g.Attributes["Label"] = "Label #" + (++i).ToString(); Polyline line = new Polyline(FromArray(-100,-30, -80,0, -60,-30, -40,0), SpatialReferences.Wgs84); var graphic = new Graphic(line, (Esri.ArcGISRuntime.Symbology.Symbol)Resources["OutlinedAndDashedSymbol"]); graphic.Attributes["Label"] = "OutlinedAndDashedSymbol"; layer.Graphics.Add(graphic); Polygon polygon = new Polygon(FromArray(-30,-30, 0,-30, 0,0, -15,-10, -30,0, -30,-30), SpatialReferences.Wgs84); graphic = new Graphic(polygon, (Esri.ArcGISRuntime.Symbology.Symbol)Resources["VertexFillSymbol"]); graphic.Attributes["Label"] = "VertexFillSymbol"; layer.Graphics.Add(graphic); //CIM symbols can only be created from JSON. The JSON is currently only constructed by publishing services to ArcGIS Server with advanced symbology string CIMSymbolJson = "{\"type\":\"CIMSymbolReference\",\"symbol\":{\"type\":\"CIMLineSymbol\",\"symbolLayers\":[{\"type\":\"CIMFilledStroke\",\"enable\":true,\"effects\":[{\"type\":\"CIMGeometricEffectArrow\",\"geometricEffectArrowType\":\"Block\",\"primitiveName\":null,\"width\":35}],\"capStyle\":\"Round\",\"pattern\":{\"type\":\"CIMSolidPattern\",\"color\":[0,0,0,255]},\"width\":2,\"lineStyle3D\":\"Strip\",\"alignment\":\"Center\",\"joinStyle\":\"Miter\",\"miterLimit\":10,\"patternFollowsStroke\":true}]},\"symbolName\":null}"; var cimsymbol = Esri.ArcGISRuntime.Symbology.Symbol.FromJson(CIMSymbolJson); Polyline line2 = new Polyline(FromArray(20, -30, 30, 0, 50, -30, 70, 0), SpatialReferences.Wgs84); graphic = new Graphic(line2, cimsymbol); graphic.Attributes["Label"] = "CIM Symbol"; layer.Graphics.Add(graphic); i = 0; foreach (var g in layer.Graphics) { g.Attributes["SymbolType"] = g.Symbol.GetType().Name; g.Attributes["ID"] = ++i; } }
void myDrawObject_DrawComplete(object sender, DrawEventArgs e) { _geometryService.CancelAsync(); _queryTask.CancelAsync(); Graphic clickGraphic = new Graphic(); clickGraphic.Symbol = LayoutRoot.Resources["DefaultMarkerSymbol"] as ESRI.ArcGIS.Client.Symbols.Symbol; clickGraphic.Geometry = e.Geometry; // Input spatial reference for buffer operation defined by first feature of input geometry array clickGraphic.Geometry.SpatialReference = MyMap.SpatialReference; _pointAndBufferGraphicsLayer.ClearGraphics(); _resultsGraphicsLayer.ClearGraphics(); clickGraphic.SetZIndex(2); _pointAndBufferGraphicsLayer.Graphics.Add(clickGraphic); // If buffer spatial reference is GCS and unit is linear, geometry service will do geodesic buffering ESRI.ArcGIS.Client.Tasks.BufferParameters bufferParams = new ESRI.ArcGIS.Client.Tasks.BufferParameters() { BufferSpatialReference = new SpatialReference(4326), OutSpatialReference = MyMap.SpatialReference, Unit = LinearUnit.Meter, }; bufferParams.Distances.Add(100); bufferParams.Features.Add(clickGraphic); _geometryService.BufferAsync(bufferParams); }
private void MyDrawObject_DrawComplete(object sender, DrawEventArgs args) { ESRI.ArcGIS.Client.Geometry.Polygon polygon = args.Geometry as ESRI.ArcGIS.Client.Geometry.Polygon; polygon.SpatialReference = MyMap.SpatialReference; Graphic graphic = new Graphic() { Symbol = LayoutRoot.Resources["DefaultFillSymbol"] as ESRI.ArcGIS.Client.Symbols.Symbol, Geometry = polygon, }; GeometryService geometryService = new GeometryService("http://serverapps101.esri.com/arcgis/rest/services/Geometry/GeometryServer"); geometryService.AreasAndLengthsCompleted += GeometryService_AreasAndLengthsCompleted; geometryService.Failed += GeometryService_Failed; GraphicsLayer graphicsLayer = MyMap.Layers["MyGraphicsLayer"] as GraphicsLayer; graphicsLayer.Graphics.Add(graphic); List<Graphic> graphicList = new List<Graphic>(); graphicList.Add(graphic); // Since there are multiple overloads for AreasAndLengthsAsync, make sure to use appropriate signature with correct parameter types. geometryService.AreasAndLengthsAsync(graphicList,null,null, (CalculationType)calculationTypeCombo.SelectedValue ); // GeometryService.AreasAndLengths returns distances and areas in the units of the spatial reference. // The units in the map view's projection is decimal degrees. // Use the Project method to convert graphic points to a projection that uses a measured unit (e.g. meters). // If the map units are in measured units, the call to Project is unnecessary. // Important: Use a projection appropriate for your area of interest. }
protected override Graphic OnCreateGraphic(GraphicCollection cluster, MapPoint point, int maxClusterCount) { if (cluster.Count == 1) return cluster[0]; double sum = 0; foreach (var g in cluster) { if (!g.Attributes.ContainsKey("Poi")) continue; try { var poi = g.Attributes["Poi"] as PoI; if (poi == null) continue; if (poi.Labels.ContainsKey(AggregateLabel)) sum += Convert.ToDouble(poi.Labels[AggregateLabel]); } catch { } } //double size = (sum + 450) / 30; var size = (Math.Log(sum * SymbolScale / 10) * 10 + 20); if (size < 12) size = 12; var graphic = new Graphic { Symbol = new ClusterSymbol { Size = size }, Geometry = point }; graphic.Attributes.Add("Count", sum); graphic.Attributes.Add("Size", size); graphic.Attributes.Add("Color", InterpolateColor(size - 12, 100)); return graphic; }
private async void FindAddressButton_Click(object sender, RoutedEventArgs e) { OnlineLocatorTask locator = GetLocation(); var findParams = new OnlineLocatorFindParameters(AddressTextBox.Text); findParams.OutSpatialReference = MyMapView.SpatialReference; findParams.SourceCountry = "US"; var results = await locator.FindAsync(findParams, new System.Threading.CancellationToken()); if (results.Count > 0) { var firstMatch = results[0].Feature; var matchLocation = firstMatch.Geometry as MapPoint; var matchSym = new PictureMarkerSymbol(); var pictureURI = new Uri("http://static.arcgis.com/images/Symbols/Basic/GreenStickpin.png"); await matchSym.SetSourceAsync(pictureURI); var matchGraphic = new Graphic(matchLocation, matchSym); var graphicsLayer = MyMap.Layers["GeocodeResults"] as GraphicsLayer; graphicsLayer.Graphics.Add(matchGraphic); var matchExtent = new Envelope(matchLocation.X - 100, matchLocation.Y - 100, matchLocation.X + 100, matchLocation.Y + 100); await MyMapView.SetViewAsync(matchExtent); } }
private void MyDrawObject_DrawComplete(object sender, DrawEventArgs args) { MyDrawObject.IsEnabled = false; ESRI.ArcGIS.Client.Geometry.Polyline polyline = args.Geometry as ESRI.ArcGIS.Client.Geometry.Polyline; polyline.SpatialReference = MyMap.SpatialReference; Graphic polylineGraphic = new Graphic() { Geometry = polyline }; List<Graphic> polylineList = new List<Graphic>(); polylineList.Add(polylineGraphic); GeometryService geometryService = new GeometryService("http://sampleserver3.arcgisonline.com/ArcGIS/rest/services/Geometry/GeometryServer"); geometryService.AutoCompleteCompleted += GeometryService_AutoCompleteCompleted; geometryService.Failed += GeometryService_Failed; GraphicsLayer graphicsLayer = MyMap.Layers["ParcelsGraphicsLayer"] as GraphicsLayer; List<Graphic> polygonList = new List<Graphic>(); foreach (Graphic g in graphicsLayer.Graphics) { g.Geometry.SpatialReference = MyMap.SpatialReference; polygonList.Add(g); } geometryService.AutoCompleteAsync(polygonList, polylineList); }
private void UpdateUIFromMapPoint(MapPoint selectedPoint) { // Remove event handlers temporarily UtmTextField.TextChanged -= InputTextChanged; DmsTextField.TextChanged -= InputTextChanged; DecimalDegreesTextField.TextChanged -= InputTextChanged; UsngTextField.TextChanged -= InputTextChanged; try { // Check if the selected point can be formatted into coordinates. CoordinateFormatter.ToLatitudeLongitude(selectedPoint, LatitudeLongitudeFormat.DecimalDegrees, 0); } catch (Exception e) { // Check if the excpetion is because the coordinates are out of range. if (e.Message == "Invalid argument: coordinates are out of range") { // Set all of the text fields to contain the error message. DecimalDegreesTextField.Text = "Out of range"; DmsTextField.Text = "Out of range"; UtmTextField.Text = "Out of range"; UsngTextField.Text = "Out of range"; // Clear the selectionss symbol. MyMapView.GraphicsOverlays[0].Graphics.Clear(); // Restore event handlers UtmTextField.TextChanged += InputTextChanged; DmsTextField.TextChanged += InputTextChanged; DecimalDegreesTextField.TextChanged += InputTextChanged; UsngTextField.TextChanged += InputTextChanged; } return; } // Update the decimal degrees text DecimalDegreesTextField.Text = CoordinateFormatter.ToLatitudeLongitude(selectedPoint, LatitudeLongitudeFormat.DecimalDegrees, 4); // Update the degrees, minutes, seconds text DmsTextField.Text = CoordinateFormatter.ToLatitudeLongitude(selectedPoint, LatitudeLongitudeFormat.DegreesMinutesSeconds, 1); // Update the UTM text UtmTextField.Text = CoordinateFormatter.ToUtm(selectedPoint, UtmConversionMode.NorthSouthIndicators, true); // Update the USNG text UsngTextField.Text = CoordinateFormatter.ToUsng(selectedPoint, 4, true); // Clear existing graphics overlays MyMapView.GraphicsOverlays[0].Graphics.Clear(); // Create a symbol to symbolize the point SimpleMarkerSymbol symbol = new SimpleMarkerSymbol(SimpleMarkerSymbolStyle.X, Colors.Yellow, 20); // Create the graphic Graphic symbolGraphic = new Graphic(selectedPoint, symbol); // Add the graphic to the graphics overlay MyMapView.GraphicsOverlays[0].Graphics.Add(symbolGraphic); // Restore event handlers UtmTextField.TextChanged += InputTextChanged; DmsTextField.TextChanged += InputTextChanged; DecimalDegreesTextField.TextChanged += InputTextChanged; UsngTextField.TextChanged += InputTextChanged; }
public AnimatedItemEffect(int sourceX, int sourceY, int sourceZ, Graphic graphic, Hue hue, int duration) : this(graphic, hue, duration) { SetSource(sourceX, sourceY, sourceZ); }
public AnimatedItemEffect(Serial source, Graphic graphic, Hue hue, int duration) : this(source, 0, 0, 0, graphic, hue, duration) { }
public AnimatedItemEffect(GameObject source, Graphic graphic, Hue hue, int duration) : this(graphic, hue, duration) { SetSource(source); }
private void PerformUnion(bool unionBuffers) { try { // Call a function to delete any existing buffer polygons so they can be recreated. ClearBufferPolygons(); // Iterate all point graphics and create a list of map points and buffer distances for each. List <MapPoint> bufferMapPoints = new List <MapPoint>(); List <double> bufferDistances = new List <double>(); foreach (Graphic bufferGraphic in _myMapView.GraphicsOverlays["buffers"].Graphics) { // Only use point graphics. if (bufferGraphic.Geometry.GeometryType == GeometryType.Point) { // Get the geometry (map point) from the graphic. MapPoint bufferLocation = bufferGraphic.Geometry as MapPoint; // Read the "distance" attribute to get the buffer distance entered when the point was tapped. double bufferDistanceFeet = (double)bufferGraphic.Attributes["distance"]; // Add the point and the corresponding distance to the lists. bufferMapPoints.Add(bufferLocation); bufferDistances.Add(bufferDistanceFeet); } } // Call GeometryEngine.Buffer with a list of map points and a list of buffered distances. IEnumerable <Geometry> bufferPolygons = GeometryEngine.Buffer(bufferMapPoints, bufferDistances, unionBuffers); // Create the outline for the buffered polygons. SimpleLineSymbol bufferPolygonOutlineSymbol = new SimpleLineSymbol(SimpleLineSymbolStyle.Solid, Color.DarkBlue, 3); // Loop through all the geometries in the buffer results. There will be one buffered polygon if // the result geometries were unioned. Otherwise, there will be one buffer per input geometry. foreach (Geometry poly in bufferPolygons) { // Create a random color to use for buffer polygon fill. Color bufferPolygonColor = GetRandomColor(); // Create simple fill symbol for the buffered polygon using the fill color and outline. SimpleFillSymbol bufferPolygonFillSymbol = new SimpleFillSymbol(SimpleFillSymbolStyle.Solid, bufferPolygonColor, bufferPolygonOutlineSymbol); // Create a new graphic for the buffered polygon using the fill symbol. Graphic bufferPolygonGraphic = new Graphic(poly, bufferPolygonFillSymbol) { // Specify a z-index of 0 to ensure the polygons draw below the tap points. ZIndex = 0 }; // Add the buffered polygon graphic to the graphics overlay. _myMapView.GraphicsOverlays[0].Graphics.Add(bufferPolygonGraphic); } } catch (Exception ex) { // Display an error message if there is a problem generating the buffers. UIAlertController alertController = UIAlertController.Create("Unable to create buffer polygons", ex.Message, UIAlertControllerStyle.Alert); alertController.AddAction(UIAlertAction.Create("OK", UIAlertActionStyle.Default, null)); PresentViewController(alertController, true, null); } }
private async void Initialize() { // Apply appropriate maps to the scene and the inset map view InsetMapView.Map = new Map(Basemap.CreateImagery()); MySceneView.Scene = new Scene(Basemap.CreateImagery()); // Update the mission selection UI MissionSelectionBox.ItemsSource = _missionToItemId.Keys; MissionSelectionBox.SelectedIndex = 0; // Wire up the selection change event to call the ChangeMission method; this method resets the animation and starts a new mission MissionSelectionBox.SelectionChanged += async(sender, args) => { await ChangeMission(args.AddedItems[0].ToString()); }; // Apply the elevation source Surface surface = new Surface(); ElevationSource elevationSource = new ArcGISTiledElevationSource(_elevationServiceUrl); surface.ElevationSources.Add(elevationSource); MySceneView.Scene.BaseSurface = surface; // Create and add the graphics overlay GraphicsOverlay sceneOverlay = new GraphicsOverlay { SceneProperties = { SurfacePlacement = SurfacePlacement.Absolute } }; MySceneView.GraphicsOverlays.Add(sceneOverlay); // Create a renderer to handle updating plane's orientation SimpleRenderer renderer3D = new SimpleRenderer(); RendererSceneProperties renderProperties = renderer3D.SceneProperties; // Use expressions to keep the renderer properties updated as parameters of the rendered object renderProperties.HeadingExpression = "[HEADING]"; renderProperties.PitchExpression = "[PITCH]"; renderProperties.RollExpression = "[ROLL]"; // Apply the renderer to the scene view's overlay sceneOverlay.Renderer = renderer3D; // Create renderer to symbolize plane and update plane orientation in the inset map SimpleRenderer renderer2D = new SimpleRenderer(); // Create the symbol that will be used for the plane SimpleMarkerSymbol plane2DSymbol = new SimpleMarkerSymbol(SimpleMarkerSymbolStyle.Triangle, Color.Blue, 10); // Apply the symbol to the renderer renderer2D.Symbol = plane2DSymbol; // Apply a rotation expression to the renderer renderer2D.RotationExpression = "[ANGLE]"; // Update the inset map with a new GraphicsOverlay based on the renderer GraphicsOverlay insetMapOperlay = new GraphicsOverlay { Renderer = renderer2D }; InsetMapView.GraphicsOverlays.Add(insetMapOperlay); // Create placeholder graphic for showing the mission route in the inset map SimpleLineSymbol routeSymbol = new SimpleLineSymbol(SimpleLineSymbolStyle.Solid, Color.Red, 2); _routeGraphic = new Graphic { Symbol = routeSymbol }; insetMapOperlay.Graphics.Add(_routeGraphic); // Create the plane graphic; this is symbolized as a blue triangle because of renderer implemented above // Create the attribute dictionary Dictionary <string, object> plane2DAttributes = new Dictionary <string, object>(); // Set the angle for the plane graphic plane2DAttributes["ANGLE"] = 0f; // Create the graphic from the attributes and the initial point _plane2D = new Graphic(new MapPoint(0, 0, SpatialReferences.Wgs84), plane2DAttributes); // Add the plane graphic to the inset map via the overlay insetMapOperlay.Graphics.Add(_plane2D); try { // Create the model graphic for the plane // Get the path to the 3D model string modelPath = GetModelPath(); // Create the scene symbol from the path to the model ModelSceneSymbol plane3DSymbol = await ModelSceneSymbol.CreateAsync(new Uri(modelPath), 1.0); // Create the graphic with an initial location and the plane symbol _plane3D = new Graphic(new MapPoint(0, 0, 0, SpatialReferences.Wgs84), plane3DSymbol); // Add the plane to the overlay sceneOverlay.Graphics.Add(_plane3D); // Create the orbit camera controller to follow the plane _orbitCameraController = new OrbitGeoElementCameraController(_plane3D, 20.0) { CameraPitchOffset = 75.0 }; MySceneView.CameraController = _orbitCameraController; // Create a timer; this will enable animating the plane // The value is the duration of the timer in milliseconds. This controls the speed of the animation (fps) _animationTimer = new Timer(60) { Enabled = true, AutoReset = true }; // Move the plane every time the timer expires _animationTimer.Elapsed += AnimatePlane; // Set the initial mission for when the sample loads await ChangeMission(_missionToItemId.Keys.First()); } catch (Exception e) { MessageBox.Show(e.ToString(), "Error"); } }
private async void OnGeoViewTapped(object sender, GeoViewInputEventArgs e) { try { IsBusy.Visibility = Visibility.Visible; Status.Text = "Identifying trace locations..."; // Set whether the user is adding a starting point or a barrier. bool isAddingStart = IsAddingStartingLocations.IsChecked.Value; // Identify the feature to be used. IEnumerable <IdentifyLayerResult> identifyResult = await MyMapView.IdentifyLayersAsync(e.Position, 10.0, false); // Check that a results from a layer were identified from the user input. if (!identifyResult.Any()) { return; } // Identify the selected feature. IdentifyLayerResult layerResult = identifyResult?.FirstOrDefault(); ArcGISFeature feature = layerResult?.GeoElements?.FirstOrDefault() as ArcGISFeature; // Check that a feature was identified from the layer. if (feature == null) { return; } // Create element with `terminal` for junction feature or with `fractionAlong` for edge feature. UtilityElement element = null; // Select default terminal or display possible terminals for the junction feature. UtilityNetworkSource networkSource = _utilityNetwork.Definition.GetNetworkSource(feature.FeatureTable.TableName); // Check if the network source is a junction or an edge. if (networkSource.SourceType == UtilityNetworkSourceType.Junction) { // Get the UtilityAssetGroup from the feature. string assetGroupFieldName = ((ArcGISFeatureTable)feature.FeatureTable).SubtypeField ?? "ASSETGROUP"; int assetGroupCode = Convert.ToInt32(feature.Attributes[assetGroupFieldName]); UtilityAssetGroup assetGroup = networkSource?.AssetGroups?.FirstOrDefault(g => g.Code == assetGroupCode); // Get the UtilityAssetType from the feature. int assetTypeCode = Convert.ToInt32(feature.Attributes["ASSETTYPE"]); UtilityAssetType assetType = assetGroup?.AssetTypes?.FirstOrDefault(t => t.Code == assetTypeCode); // Get the list of terminals for the feature. IEnumerable <UtilityTerminal> terminals = assetType?.TerminalConfiguration?.Terminals; // If there is more than one terminal, prompt the user to select a terminal. if (terminals.Count() > 1) { // Ask the user to choose the terminal. UtilityTerminal terminal = await WaitForTerminal(terminals); // Create a UtilityElement with the terminal. element = _utilityNetwork.CreateElement(feature, terminal); Status.Text = $"Terminal: {terminal?.Name ?? "default"}"; } else { element = _utilityNetwork.CreateElement(feature, terminals.FirstOrDefault()); Status.Text = $"Terminal: {element.Terminal?.Name ?? "default"}"; } } else if (networkSource.SourceType == UtilityNetworkSourceType.Edge) { element = _utilityNetwork.CreateElement(feature); // Compute how far tapped location is along the edge feature. if (feature.Geometry is Polyline line) { line = GeometryEngine.RemoveZ(line) as Polyline; // Set how far the element is along the edge. element.FractionAlongEdge = GeometryEngine.FractionAlong(line, e.Location, -1); Status.Text = $"Fraction along edge: {element.FractionAlongEdge}"; } } // Check that the element can be added to the parameters. if (element == null) { return; } // Build the utility trace parameters. if (_parameters == null) { IEnumerable <UtilityElement> startingLocations = Enumerable.Empty <UtilityElement>(); _parameters = new UtilityTraceParameters(UtilityTraceType.Connected, startingLocations); } if (isAddingStart) { _parameters.StartingLocations.Add(element); } else { _parameters.Barriers.Add(element); } // Add a graphic for the new utility element. Graphic traceLocationGraphic = new Graphic(feature.Geometry as MapPoint ?? e.Location, isAddingStart ? _startingPointSymbol : _barrierPointSymbol); MyMapView.GraphicsOverlays.FirstOrDefault()?.Graphics.Add(traceLocationGraphic); } catch (Exception ex) { Status.Text = "Identifying locations failed..."; await new MessageDialog(ex.Message, "Error").ShowAsync(); } finally { if (Status.Text.Equals("Identifying trace locations...")) { Status.Text = "Could not identify location."; } IsBusy.Visibility = Visibility.Collapsed; } }
private async void Initialize() { // Create the scene with an imagery basemap. MySceneView.Scene = new Scene(Basemap.CreateImagery()); // Add the elevation surface. ArcGISTiledElevationSource tiledElevationSource = new ArcGISTiledElevationSource(_elevationUri); Surface baseSurface = new Surface { ElevationSources = { tiledElevationSource } }; MySceneView.Scene.BaseSurface = baseSurface; // Add buildings. ArcGISSceneLayer sceneLayer = new ArcGISSceneLayer(_buildingsUri); MySceneView.Scene.OperationalLayers.Add(sceneLayer); await sceneLayer.LoadAsync(); // Configure graphics overlay for the tank and add the overlay to the SceneView. _tankOverlay.SceneProperties.SurfacePlacement = SurfacePlacement.Relative; MySceneView.GraphicsOverlays.Add(_tankOverlay); // Configure heading expression for tank; this will allow the // viewshed to update automatically based on the tank's position. SimpleRenderer renderer3D = new SimpleRenderer(); renderer3D.SceneProperties.HeadingExpression = "[HEADING]"; _tankOverlay.Renderer = renderer3D; // Create the tank graphic - get the model path. string modelPath = GetModelPath(); // - Create the symbol and make it 10x larger (to be the right size relative to the scene). ModelSceneSymbol tankSymbol = await ModelSceneSymbol.CreateAsync(new Uri(modelPath), 10); // - Adjust the position. tankSymbol.Heading = 90; // - The tank will be positioned relative to the scene surface by its bottom. // This ensures that the tank is on the ground rather than partially under it. tankSymbol.AnchorPosition = SceneSymbolAnchorPosition.Bottom; // - Create the graphic. _tank = new Graphic(new MapPoint(4.847969, 45.746452, SpatialReferences.Wgs84), tankSymbol); // - Update the heading. _tank.Attributes["HEADING"] = 0.0; // - Add the graphic to the overlay. _tankOverlay.Graphics.Add(_tank); // Create a viewshed for the tank. GeoElementViewshed geoViewshed = new GeoElementViewshed( geoElement: _tank, horizontalAngle: 90.0, verticalAngle: 40.0, minDistance: 0.1, maxDistance: 250.0, headingOffset: 0.0, pitchOffset: 0.0) { // Offset viewshed observer location to top of tank. OffsetZ = 3.0 }; // Create the analysis overlay and add to the scene. AnalysisOverlay overlay = new AnalysisOverlay(); overlay.Analyses.Add(geoViewshed); MySceneView.AnalysisOverlays.Add(overlay); // Create a camera controller to orbit the tank. OrbitGeoElementCameraController cameraController = new OrbitGeoElementCameraController(_tank, 200.0) { CameraPitchOffset = 45.0 }; // - Apply the camera controller to the SceneView. MySceneView.CameraController = cameraController; // Create a timer; this will enable animating the tank. Windows.UI.Xaml.DispatcherTimer animationTimer = new Windows.UI.Xaml.DispatcherTimer() { Interval = new TimeSpan(0, 0, 0, 0, 60) }; // - Move the tank every time the timer expires. animationTimer.Tick += (o, e) => { AnimateTank(); }; // - Start the timer. animationTimer.Start(); // Allow the user to click to define a new destination. MySceneView.GeoViewTapped += (sender, args) => { _tankEndPoint = args.Location; }; }
// Verse.GhostDrawer public static bool HeronDoorGhostHandler(IntVec3 center, Rot4 rot, ThingDef thingDef, Graphic baseGraphic, Color ghostCol, AltitudeLayer drawAltitude) { if (thingDef is DoorExpandedDef def && def.fixedPerspective) { Graphic graphic = GhostUtility.GhostGraphicFor(baseGraphic, thingDef, ghostCol); //Graphic graphic = Traverse.Create(typeof(GhostDrawer)).Method("GhostGraphicFor", new object[] { thingDef.graphic, thingDef, ghostCol }).GetValue<Graphic>(); Vector3 loc = GenThing.TrueCenter(center, rot, thingDef.Size, drawAltitude.AltitudeFor()); for (int i = 0; i < 2; i++) { bool flipped = (i != 0) ? true : false; Building_DoorExpanded.DrawParams(def, loc, rot, out var mesh, out var matrix, mod: 0, flipped: flipped); Graphics.DrawMesh(mesh: mesh, matrix: matrix, material: graphic.MatAt(rot: rot, thing: null), layer: 0); } if (thingDef?.PlaceWorkers?.Count > 0) { for (int i = 0; i < thingDef.PlaceWorkers.Count; i++) { thingDef.PlaceWorkers[index : i] .DrawGhost(def : thingDef, center : center, rot : rot, ghostCol : ghostCol); } } return(false); } return(true); }
private void buttonCreateMeme_Click(object sender, RoutedEventArgs e) { var meme = new Meme(); meme.textTop.Text = TopText; meme.textBottom.Text = BottomText; meme.Owner = this; meme.ShowDialog(); if (String.IsNullOrWhiteSpace(TopText) && String.IsNullOrWhiteSpace(BottomText)) { return; } var fontFamily = System.Drawing.FontFamily.Families.FirstOrDefault(ff => ff.Name == FontName); if (fontFamily == null) { fontFamily = System.Drawing.FontFamily.GenericSansSerif; } EditedImage = (Bitmap)OriginalImage.Clone(); Graphic = Graphics.FromImage(EditedImage); Graphic.SmoothingMode = SmoothingMode.AntiAlias; int pointSize = 1; Font font = new Font(fontFamily, pointSize, System.Drawing.FontStyle.Bold); SizeF lastMeasurement = SizeF.Empty; System.Drawing.Point drawPoint = System.Drawing.Point.Empty; GraphicsPath path = new GraphicsPath(); if (!String.IsNullOrWhiteSpace(TopText)) { while (lastMeasurement.Width < SourceSize.Width - 25 && pointSize < Settings.Current.MemeMaxFontSize) { pointSize++; font = new Font(fontFamily, pointSize, System.Drawing.FontStyle.Bold); lastMeasurement = Graphic.MeasureString(TopText, font); } pointSize--; font = new Font(fontFamily, pointSize, System.Drawing.FontStyle.Bold); lastMeasurement = Graphic.MeasureString(TopText, font); drawPoint = new System.Drawing.Point((int)(SourceSize.Width / 2), 0); path = new GraphicsPath(); path.AddString(TopText, fontFamily, (int)System.Drawing.FontStyle.Bold, Graphic.DpiY * pointSize / 72, drawPoint, new StringFormat() { Alignment = StringAlignment.Center }); Graphic.DrawPath(new System.Drawing.Pen(System.Drawing.Brushes.Black, pointSize / 4), path); Graphic.FillPath(System.Drawing.Brushes.White, path); pointSize = 1; font = new Font(fontFamily, pointSize, System.Drawing.FontStyle.Bold); lastMeasurement = SizeF.Empty; } if (!String.IsNullOrWhiteSpace(BottomText)) { while (lastMeasurement.Width < SourceSize.Width - 25 && pointSize < Settings.Current.MemeMaxFontSize) { pointSize++; font = new Font(fontFamily, pointSize, System.Drawing.FontStyle.Bold); lastMeasurement = Graphic.MeasureString(BottomText, font); } pointSize--; font = new Font(fontFamily, pointSize, System.Drawing.FontStyle.Bold); lastMeasurement = Graphic.MeasureString(BottomText, font); drawPoint = new System.Drawing.Point((int)(SourceSize.Width / 2), (int)SourceSize.Height - (int)lastMeasurement.Height); path = new GraphicsPath(); path.AddString(BottomText, fontFamily, (int)System.Drawing.FontStyle.Bold, Graphic.DpiY * pointSize / 72, drawPoint, new StringFormat() { Alignment = StringAlignment.Center }); Graphic.DrawPath(new System.Drawing.Pen(System.Drawing.Brushes.Black, pointSize / 4), path); Graphic.FillPath(System.Drawing.Brushes.White, path); } Graphic.Save(); using (var ms = new MemoryStream()) { EditedImage.Save(ms, System.Drawing.Imaging.ImageFormat.Png); ImageSourceFrame = BitmapFrame.Create(ms, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.OnLoad); imageMain.Source = ImageSourceFrame; } }
/// <summary> /// 타겟이었던 그래픽 소스를 동적으로 삭제함. /// </summary> /// <param name="p_graphic"></param> public void RemoveChangeTarget(Graphic p_graphic) { changeGraphics.Remove(p_graphic); }
void Start() { rd = this.GetComponent <Graphic>(); rd.color = rd.color.SetA(0f); }
// Start is called before the first frame update void Start() { graphic = GetComponent <Graphic>(); mat = graphic.material; }
private async Task SendFrame() { IntPtr hWnd = IntPtr.Zero; IntPtr hDC = IntPtr.Zero; IntPtr graphDC = IntPtr.Zero; try { hWnd = User32.GetDesktopWindow(); hDC = User32.GetWindowDC(hWnd); graphDC = Graphic.GetHdc(); var copyResult = GDI32.BitBlt(graphDC, 0, 0, screenShot.TotalWidth, screenShot.TotalHeight, hDC, 0 + offsetX, 0 + offsetY, GDI32.TernaryRasterOperations.SRCCOPY | GDI32.TernaryRasterOperations.CAPTUREBLT); if (!copyResult) { Graphic.ReleaseHdc(graphDC); Graphic.Clear(System.Drawing.Color.White); var font = new Font(System.Drawing.FontFamily.GenericSansSerif, 30, System.Drawing.FontStyle.Bold); Graphic.DrawString("Waiting for screen capture...", font, System.Drawing.Brushes.Black, new PointF((screenShot.TotalWidth / 2), screenShot.TotalHeight / 2), new StringFormat() { Alignment = StringAlignment.Center }); } else { Graphic.ReleaseHdc(graphDC); User32.ReleaseDC(hWnd, hDC); } // Get cursor information to draw on the screenshot. var ci = new User32.CursorInfo(); ci.cbSize = Marshal.SizeOf(ci); User32.GetCursorInfo(out ci); if (ci.flags == User32.CURSOR_SHOWING) { using (var icon = System.Drawing.Icon.FromHandle(ci.hCursor)) { Graphic.DrawIcon(icon, ci.ptScreenPos.x, ci.ptScreenPos.y); } } if (sendFullScreenshot) { var request = new { Type = "Bounds", Width = screenShot.TotalWidth, Height = screenShot.TotalHeight }; await SocketSend(request); using (var ms = new MemoryStream()) { screenShot.CurrentFrame.Save(ms, ImageFormat.Jpeg); ms.WriteByte(0); ms.WriteByte(0); ms.WriteByte(0); ms.WriteByte(0); ms.WriteByte(0); ms.WriteByte(0); await Socket.SendAsync(new ArraySegment <byte>(ms.ToArray()), WebSocketMessageType.Binary, true, CancellationToken.None); sendFullScreenshot = false; return; } } NewData = screenShot.GetNewData(); if (NewData == null) { await Task.Delay(100); // Ignore async warning here since it's intentional. This is to prevent deadlock. #pragma warning disable SendFrame(); #pragma warning restore } else { using (var ms = new MemoryStream()) { screenShot.SaveCroppedFrame(ms); // Add x,y coordinates of top-left of image so receiver knows where to draw it. foreach (var metaByte in NewData) { ms.WriteByte(metaByte); } await Socket.SendAsync(new ArraySegment <byte>(ms.ToArray()), WebSocketMessageType.Binary, true, CancellationToken.None); } } screenShot.CloneLastFrame(); } catch (Exception ex) { WriteToLog(ex); if (graphDC != IntPtr.Zero) { Graphic.ReleaseHdc(graphDC); } if (hDC != IntPtr.Zero) { User32.ReleaseDC(hWnd, hDC); } capturing = false; stackMain.Visibility = Visibility.Collapsed; stackReconnect.Visibility = Visibility.Visible; textAgentStatus.FontWeight = FontWeights.Normal; textAgentStatus.Foreground = new SolidColorBrush(Colors.Black); textAgentStatus.Text = "Not Connected"; } }
public static void ToggleColor(Graphic g, bool bToggled) { g.color = bToggled ? Color.white : new Color(0.2f, 0.2f, 0.2f); }
/// <summary> /// 타겟이 될 그래픽 소스를 동적으로 할당함. /// </summary> public void AddChangeTarget(Graphic p_graphic) { changeGraphics.Add(p_graphic); }
private void CopyPreserveAspect(bool isPreserveAspect, Graphic graphic, UIPreserveAspect copy) { copy.preserveAspect = isPreserveAspect; copy.rawImage = graphic as RawImage; }
private async void OnGeoViewTapped(object sender, Esri.ArcGISRuntime.Xamarin.Forms.GeoViewInputEventArgs e) { try { BusyIndicator.IsVisible = true; Status.Text = "Identifying trace locations..."; // Identify the feature to be used. IEnumerable <IdentifyLayerResult> identifyResult = await MyMapView.IdentifyLayersAsync(e.Position, 10.0, false); ArcGISFeature feature = identifyResult?.FirstOrDefault()?.GeoElements?.FirstOrDefault() as ArcGISFeature; if (feature == null) { return; } // Create element from the identified feature. UtilityElement element = _utilityNetwork.CreateElement(feature); if (element.NetworkSource.SourceType == UtilityNetworkSourceType.Junction) { // Select terminal for junction feature. IEnumerable <UtilityTerminal> terminals = element.AssetType.TerminalConfiguration?.Terminals; if (terminals?.Count() > 1) { element.Terminal = await WaitForTerminal(terminals); } Status.Text = $"Terminal: {element.Terminal?.Name ?? "default"}"; } else if (element.NetworkSource.SourceType == UtilityNetworkSourceType.Edge) { // Compute how far tapped location is along the edge feature. if (feature.Geometry is Polyline line) { line = GeometryEngine.RemoveZ(line) as Polyline; double fraction = GeometryEngine.FractionAlong(line, e.Location, -1); if (double.IsNaN(fraction)) { return; } element.FractionAlongEdge = fraction; Status.Text = $"Fraction along edge: {element.FractionAlongEdge}"; } } // Check whether starting location or barrier is added to update the right collection and symbology. Symbol symbol = null; if (IsAddingStartingLocations.IsEnabled != true) { _startingLocations.Add(element); symbol = _startingPointSymbol; } else { _barriers.Add(element); symbol = _barrierPointSymbol; } // Add a graphic for the new utility element. Graphic traceLocationGraphic = new Graphic(feature.Geometry as MapPoint ?? e.Location, symbol); MyMapView.GraphicsOverlays.FirstOrDefault()?.Graphics.Add(traceLocationGraphic); } catch (Exception ex) { Status.Text = "Identifying locations failed."; await Application.Current.MainPage.DisplayAlert(ex.GetType().Name, ex.Message, "OK"); } finally { if (Status.Text.Equals("Identifying trace locations...")) { Status.Text = "Could not identify location."; } BusyIndicator.IsVisible = false; } }
public AnimatedItemEffect(Serial sourceSerial, int sourceX, int sourceY, int sourceZ, Graphic graphic, Hue hue, int duration) : this(graphic, hue, duration) { sbyte zSrc = (sbyte)sourceZ; Entity source = World.Get(sourceSerial); if (source != null) { if (sourceSerial.IsMobile) { Mobile mob = (Mobile)source; if (mob != World.Player && !mob.IsMoving && (sourceX != 0 || sourceY != 0 || sourceZ != 0)) { mob.Position = new Position((ushort)sourceX, (ushort)sourceY, zSrc); } SetSource(mob); } else if (sourceSerial.IsItem) { Item item = (Item)source; if (sourceX != 0 || sourceY != 0 || sourceZ != 0) { item.Position = new Position((ushort)sourceX, (ushort)sourceY, zSrc); } SetSource(item); } else { SetSource(sourceX, sourceY, sourceZ); } } else { SetSource(sourceX, sourceY, sourceZ); } }
private async void SolveButton_Click(object sender, RoutedEventArgs e) { try { if (_stops.Count == 0) { return; } RouteParameters routeParams = await _onlineRouteTask.GetDefaultParametersAsync(); GenerateBarriers(); FeaturesAsFeature stopsFeatures = new FeaturesAsFeature(); stopsFeatures.Features = _stops; routeParams.Stops = stopsFeatures; if (_polylineBarriers.Count > 0) { FeaturesAsFeature polylineBarrierFeatures = new FeaturesAsFeature(); polylineBarrierFeatures.Features = _polylineBarriers; routeParams.PolylineBarriers = polylineBarrierFeatures; } if (_polygonBarriers.Count > 0) { FeaturesAsFeature polygonBarrierFeatures = new FeaturesAsFeature(); polygonBarrierFeatures.Features = _polygonBarriers; routeParams.PolygonBarriers = polygonBarrierFeatures; } List <AttributeParameterValue> aps = new List <AttributeParameterValue>(); AttributeParameterValue apv = GetAttributeParameterValue(AttributeParameter2.SelectionBoxItem.ToString().Trim()); if (apv != null) { aps.Add(apv); } //routeParams.AttributeParameterValues = aps; //routeParams.ReturnDirections = ReturnDirections2.IsChecked.HasValue ? ReturnDirections2.IsChecked.Value : false; routeParams.DirectionsLanguage = String.IsNullOrEmpty(DirectionsLanguage2.Text) ? new System.Globalization.CultureInfo("en-US") : new System.Globalization.CultureInfo(DirectionsLanguage2.Text); routeParams.DirectionsLengthUnit = GetDirectionsLengthUnits(DirectionsLengthUnits2.SelectionBoxItem.ToString().Trim()); routeParams.ReturnRoutes = ReturnRoutes2.IsChecked.HasValue ? ReturnRoutes2.IsChecked.Value : false; routeParams.ReturnStops = ReturnFacilities2.IsChecked.HasValue ? ReturnFacilities2.IsChecked.Value : false; routeParams.ReturnPointBarriers = ReturnBarriers2.IsChecked.HasValue ? ReturnBarriers2.IsChecked.Value : false; routeParams.ReturnPolygonBarriers = ReturnPolygonBarriers2.IsChecked.HasValue ? ReturnPolygonBarriers2.IsChecked.Value : false; routeParams.ReturnPolylineBarriers = ReturnPolylineBarriers2.IsChecked.HasValue ? ReturnPolylineBarriers2.IsChecked.Value : false; routeParams.OutputLines = GetOutputLines(OutputLines2.SelectionBoxItem.ToString().Trim()); routeParams.OutSpatialReference = string.IsNullOrEmpty(OutputSpatialReference2.Text) ? mapView1.SpatialReference : new SpatialReference(int.Parse(OutputSpatialReference2.Text)); //routeParams.AccumulateAttributeNames = AccumulateAttributeNames2.Text.Split(','); routeParams.ImpedanceAttributeName = ImpedanceAttributeName2.Text; routeParams.RestrictionAttributeNames = RestrictionAttributeNames2.Text.Split(','); routeParams.RestrictUTurns = GetRestrictUTurns(RestrictUTurns2.SelectionBoxItem.ToString().Trim()); routeParams.UseHierarchy = UseHierarchy2.IsChecked.HasValue ? UseHierarchy2.IsChecked.Value : false; routeParams.OutputGeometryPrecision = string.IsNullOrEmpty(OutputGeometryPrecision2.Text) ? 0 : double.Parse(OutputGeometryPrecision2.Text); routeParams.OutputGeometryPrecisionUnit = GetGeometryPrecisionUnits(OutputGeometryPrecisionUnits2.SelectionBoxItem.ToString().Trim()); RouteResult result = await _onlineRouteTask.SolveAsync(routeParams); _routeGraphicsLayer.Graphics.Clear(); foreach (Route route in result.Routes) { Graphic g = route.RouteGraphic; g.Symbol = LayoutRoot.Resources["RouteSymbol"] as SimpleLineSymbol; _routeGraphicsLayer.Graphics.Add(g); } } catch (Exception ex) { var dlg = new MessageDialog(ex.Message, "Solve Failed!"); var _ = dlg.ShowAsync(); } }
public Bitmap ToBitmap() { return(Graphic.ConvertData(this.ImageData, this.PaletteData, (byte[])null, 0, (int)this.Width, (int)this.Height, this.TextureFormat, Graphic.NNSG2dCharacterFmt.NNS_G2D_CHARACTER_FMT_BMP, Convert.ToBoolean(this.Unknown1), true)); }
private void Finalize(bool isSprite, bool isTexture, bool isMaterial, Graphic source, Graphic copy) { if (isMaterial == true) { var sourceImage = source; if (sourceImage != null) { sourceImage.material = (copy.material == sourceImage.defaultMaterial ? null : copy.material); sourceImage.SetMaterialDirty(); } } else if (isSprite == true) { var sourceImage = source as Image; if (sourceImage != null) { sourceImage.sprite = (copy as Image).sprite; } } else if (isTexture == true) { var sourceImage = source as RawImage; if (sourceImage != null) { var texture = (copy as RawImage).texture; if (texture.GetID() != sourceImage.texture.GetID()) { MovieSystem.Stop(this.image, sourceImage.texture.GetID()); } sourceImage.texture = texture; } } if (copy != null) { GameObject.Destroy(copy.gameObject); } }
// Handle a new selected comment record in the table view. private async void CommentsListBox_SelectionChanged(object sender, Windows.UI.Xaml.Controls.SelectionChangedEventArgs e) { // Clear selected features from the graphics overlay. _selectedFeaturesOverlay.Graphics.Clear(); // Get the selected comment feature. If there is no selection, return. ArcGISFeature selectedComment = e.AddedItems[0] as ArcGISFeature; if (selectedComment == null) { return; } // Get the map image layer that contains the service request sublayer and the service request comments table. ArcGISMapImageLayer serviceRequestsMapImageLayer = (ArcGISMapImageLayer)MyMapView.Map.OperationalLayers[0]; // Get the (non-spatial) table that contains the service request comments. ServiceFeatureTable commentsTable = serviceRequestsMapImageLayer.Tables[0]; // Get the relationship that defines related service request features for features in the comments table (this is the first and only relationship). RelationshipInfo commentsRelationshipInfo = commentsTable.LayerInfo.RelationshipInfos.FirstOrDefault(); // Create query parameters to get the related service request for features in the comments table. RelatedQueryParameters relatedQueryParams = new RelatedQueryParameters(commentsRelationshipInfo) { ReturnGeometry = true }; try { // Query the comments table to get the related service request feature for the selected comment. IReadOnlyList <RelatedFeatureQueryResult> relatedRequestsResult = await commentsTable.QueryRelatedFeaturesAsync(selectedComment, relatedQueryParams); // Get the first result. RelatedFeatureQueryResult result = relatedRequestsResult.FirstOrDefault(); // Get the first feature from the result. If it's null, warn the user and return. ArcGISFeature serviceRequestFeature = result.FirstOrDefault() as ArcGISFeature; if (serviceRequestFeature == null) { MessageDialog message = new MessageDialog("Related feature not found.", "No Feature"); await message.ShowAsync(); return; } // Load the related service request feature (so its geometry is available). await serviceRequestFeature.LoadAsync(); // Get the service request geometry (point). MapPoint serviceRequestPoint = serviceRequestFeature.Geometry as MapPoint; // Create a cyan marker symbol to display the related feature. Symbol selectedRequestSymbol = new SimpleMarkerSymbol(SimpleMarkerSymbolStyle.Circle, Color.Cyan, 14); // Create a graphic using the service request point and marker symbol. Graphic requestGraphic = new Graphic(serviceRequestPoint, selectedRequestSymbol); // Add the graphic to the graphics overlay and zoom the map view to its extent. _selectedFeaturesOverlay.Graphics.Add(requestGraphic); await MyMapView.SetViewpointCenterAsync(serviceRequestPoint, 150000); } catch (Exception ex) { await new MessageDialog(ex.ToString(), "Error").ShowAsync(); } }
public static void Initialize(TrueShadow shadow, ref ShadowRenderer renderer) { if (renderer && renderer.shadow == shadow) { renderer.gameObject.SetActive(true); return; } var obj = new GameObject($"{shadow.gameObject.name}'s Shadow") { #if LETAI_TRUESHADOW_DEBUG hideFlags = DebugSettings.Instance.showObjects ? HideFlags.DontSave : HideFlags.HideAndDontSave #else hideFlags = HideFlags.HideAndDontSave #endif }; shadow.SetHierachyDirty(); var rt = obj.AddComponent <RectTransform>(); rt.anchorMin = Vector2.zero; rt.anchorMax = Vector2.zero; Graphic graphic; var type = shadow.Baked ? GraphicType.Image : GraphicType.RawImage; switch (type) { case GraphicType.Image: var image = obj.AddComponent <Image>(); image.useSpriteMesh = true; graphic = image; break; case GraphicType.RawImage: graphic = obj.AddComponent <RawImage>(); break; default: throw new ArgumentOutOfRangeException(nameof(type), type, null); } graphic.raycastTarget = false; graphic.color = shadow.Color; renderer = obj.AddComponent <ShadowRenderer>(); renderer.shadow = shadow; renderer.rt = rt; renderer.graphic = graphic; // renderer.RecreateGraphic(shadow.Baked ? GraphicType.Image : GraphicType.RawImage); renderer.UpdateMaterial(); renderer.CanvasRenderer = obj.GetComponent <CanvasRenderer>(); renderer.CanvasRenderer.SetColor(shadow.IgnoreCasterColor ? Color.white : shadow.CanvasRenderer.GetColor()); renderer.CanvasRenderer.SetAlpha(shadow.CanvasRenderer.GetAlpha()); renderer.ReLayout(); }
private async void Initialize() { // Create scene Scene myScene = new Scene(Basemap.CreateImageryWithLabels()); // Create the elevation source ElevationSource myElevationSource = new ArcGISTiledElevationSource(_elevationUri); // Add the elevation source to the scene myScene.BaseSurface.ElevationSources.Add(myElevationSource); // Create the building scene layer ArcGISSceneLayer mySceneLayer = new ArcGISSceneLayer(_buildingsUri); // Add the building layer to the scene myScene.OperationalLayers.Add(mySceneLayer); // Add the observer to the scene // Create a graphics overlay with relative surface placement; relative surface placement allows the Z position of the observation point to be adjusted GraphicsOverlay overlay = new GraphicsOverlay() { SceneProperties = new LayerSceneProperties(SurfacePlacement.Relative) }; // Create the symbol that will symbolize the observation point SimpleMarkerSceneSymbol symbol = new SimpleMarkerSceneSymbol(SimpleMarkerSceneSymbolStyle.Sphere, Colors.Red, 10, 10, 10, SceneSymbolAnchorPosition.Bottom); // Create the observation point graphic from the point and symbol _observerGraphic = new Graphic(_observerPoint, symbol); // Add the observer to the overlay overlay.Graphics.Add(_observerGraphic); // Add the overlay to the scene MySceneView.GraphicsOverlays.Add(overlay); // Add the taxi to the scene // Create the model symbol for the taxi ModelSceneSymbol taxiSymbol = await ModelSceneSymbol.CreateAsync(await GetModelUri()); // Set the anchor position for the mode; ensures that the model appears above the ground taxiSymbol.AnchorPosition = SceneSymbolAnchorPosition.Bottom; // Create the graphic from the taxi starting point and the symbol _taxiGraphic = new Graphic(_points[0], taxiSymbol); // Add the taxi graphic to the overlay overlay.Graphics.Add(_taxiGraphic); // Create GeoElement Line of sight analysis (taxi to building) // Create the analysis _geoLine = new GeoElementLineOfSight(_observerGraphic, _taxiGraphic); // Apply an offset to the target. This helps avoid some false negatives _geoLine.TargetOffsetZ = 2; // Create the analysis overlay AnalysisOverlay myAnalysisOverlay = new AnalysisOverlay(); // Add the analysis to the overlay myAnalysisOverlay.Analyses.Add(_geoLine); // Add the analysis overlay to the scene MySceneView.AnalysisOverlays.Add(myAnalysisOverlay); // Create a timer; this will enable animating the taxi Windows.UI.Xaml.DispatcherTimer animationTimer = new Windows.UI.Xaml.DispatcherTimer() { Interval = new TimeSpan(0, 0, 0, 0, 60) }; // Move the taxi every time the timer expires animationTimer.Tick += AnimationTimer_Tick; // Start the timer animationTimer.Start(); // Subscribe to TargetVisible events; allows for updating the UI and selecting the taxi when it is visible _geoLine.TargetVisibilityChanged += Geoline_TargetVisibilityChanged; // Add the scene to the view MySceneView.Scene = myScene; // Set the viewpoint MySceneView.SetViewpoint(new Viewpoint(_observerPoint, 1000)); }
private static bool DrawIconForWeaponMemory(GoldfishModule pawnMemory, ThingDef weapon, Rect contentRect, Vector2 iconOffset) { //Log.Message("drawing memory of " + weapon.defName); var iconTex = weapon.uiIcon; Graphic g = weapon.graphicData.Graphic; Color color = getColor(weapon); Color colorTwo = getColor(weapon); Graphic g2 = weapon.graphicData.Graphic.GetColoredVersion(g.Shader, color, colorTwo); var iconRect = new Rect(contentRect.x + iconOffset.x, contentRect.y + iconOffset.y, IconSize, IconSize); //if (!contentRect.Contains(iconRect)) // return false; string label = weapon.label; Texture2D drawPocket; if (pawnMemory.IsCurrentPrimary(weapon.defName)) { drawPocket = TextureResources.drawPocketMemoryPrimary; } else { drawPocket = TextureResources.drawPocketMemory; } TooltipHandler.TipRegion(iconRect, string.Format("DrawSidearm_gizmoTooltipMemory".Translate(), weapon.label)); MouseoverSounds.DoRegion(iconRect, SoundDefOf.MouseoverCommand); if (Mouse.IsOver(iconRect)) { GUI.color = iconMouseOverColor; GUI.DrawTexture(iconRect, drawPocket); } else { GUI.color = iconBaseColor; GUI.DrawTexture(iconRect, drawPocket); } Texture resolvedIcon; if (!weapon.uiIconPath.NullOrEmpty()) { resolvedIcon = weapon.uiIcon; } else { resolvedIcon = g2.MatSingle.mainTexture; } GUI.color = color; GUI.DrawTexture(iconRect, resolvedIcon); GUI.color = Color.white; //Log.Message("done"); if (Widgets.ButtonInvisible(iconRect, true)) { return(true); } else { return(false); } }
public void SetGraphic(Graphic g) { Graphic = g; _itemData = FileManager.TileData.StaticData[Graphic]; }
public override void UpdateFirst() { _sprite = Entity.Graphic; _isPressedLastFrame = _isPressed; }
public static void Fill(OpenXmlElement docNode, XmlElement macroListXml, WordprocessingDocument wdDoc) { /* Форматированный текст для встроенных элементов */ IEnumerable <Paragraph> paragraphs = docNode.Elements <Paragraph>(); foreach (Paragraph paragraph in paragraphs) { IEnumerable <SdtRun> sdtRuns = paragraph.Elements <SdtRun>(); foreach (SdtRun sdtRun in sdtRuns) { // Из SdtProperties взять Tag для идентификации Content Control SdtProperties sdtProperties = sdtRun.GetFirstChild <SdtProperties>(); Tag tag = sdtProperties.GetFirstChild <Tag>(); // Найти в macroListXml Node макропеременной String macroVarValue = FindMacroVar(macroListXml, tag.Val); if (macroVarValue != null) { // Сохранить старый стиль Run SdtContentRun sdtContentRun = sdtRun.GetFirstChild <SdtContentRun>(); OpenXmlElement oldRunProps = sdtContentRun.GetFirstChild <Run>().GetFirstChild <RunProperties>().CloneNode(true); // Очистить Node Content Control sdtContentRun.RemoveAllChildren(); // Создать новую Run Node Run newRun = sdtContentRun.AppendChild(new Run()); // Вернуть старый стиль newRun.AppendChild(oldRunProps); // Вставить текст (без переносов строк!!!) newRun.AppendChild(new Text(macroVarValue)); } } } /* Получить остальные Content Control */ IEnumerable <SdtBlock> sdtBlocks = docNode.Elements <SdtBlock>(); foreach (SdtBlock sdtBlock in sdtBlocks) { // Получить параметры(SdtProperties) Content Control SdtProperties sdtProperties = sdtBlock.GetFirstChild <SdtProperties>(); // Получить Tag для идентификации Content Control Tag tag = sdtProperties.GetFirstChild <Tag>(); // Получить значение макроперенной из macroListXml Console.WriteLine("Tag: " + tag.Val); String macroVarValue = FindMacroVar(macroListXml, tag.Val); // Если макропеременная есть в MacroListXml if (macroVarValue != null) { Console.WriteLine("Value: " + macroVarValue); // Получить блок содержимого Content Control SdtContentBlock sdtContentBlock = sdtBlock.GetFirstChild <SdtContentBlock>(); /* Форматированный текст для абзацев */ if (sdtProperties.GetFirstChild <SdtPlaceholder>() != null && sdtContentBlock.GetFirstChild <Paragraph>() != null) { // Сохранить старый стиль параграфа ParagraphProperties oldParagraphProperties = sdtContentBlock.GetFirstChild <Paragraph>().GetFirstChild <ParagraphProperties>().CloneNode(true) as ParagraphProperties; String oldParagraphPropertiesXml = oldParagraphProperties.InnerXml; // Очистить ноду с контентом sdtContentBlock.RemoveAllChildren(); InsertText(macroVarValue, oldParagraphPropertiesXml, sdtContentBlock); } /* Таблицы */ if (sdtProperties.GetFirstChild <SdtPlaceholder>() != null && sdtContentBlock.GetFirstChild <Table>() != null) { // Получить ноду таблицы Table table = sdtContentBlock.GetFirstChild <Table>(); // Получить все строки таблицы IEnumerable <TableRow> tableRows = table.Elements <TableRow>(); // Получить вторую строку из таблицы TableRow tableRow = tableRows.ElementAt(1) as TableRow; Type tableRowType = tableRow.GetType(); // Получить все стили столбцов List <String> paragraphCellStyles = new List <string>(); IEnumerable <OpenXmlElement> tableCells = tableRow.Elements <TableCell>(); foreach (OpenXmlElement tableCell in tableCells) { String paragraphCellStyleXml = tableCell.GetFirstChild <Paragraph>().GetFirstChild <ParagraphProperties>().InnerXml; paragraphCellStyles.Add(paragraphCellStyleXml); } // Удалить все строки, после первой while (tableRows.Count <TableRow>() > 1) { TableRow lastTableRows = tableRows.Last <TableRow>(); lastTableRows.Remove(); } // Удалить последний элемент, если это не TableRow OpenXmlElement lastNode = table.LastChild; if (lastNode.GetType() != tableRowType) { lastNode.Remove(); } string[] rowDelimiters = new string[] { "|||" }; string[] columnDelimiters = new string[] { "^^^" }; // Получить массив строк из макропеременной String[] rowsXml = macroVarValue.Split(rowDelimiters, StringSplitOptions.None); int i = 0; while (i < rowsXml.Length) { // Получить строку String rowXml = rowsXml[i]; // Добавить ноду строки таблицы TableRow newTableRow = table.AppendChild(new TableRow()); // Получить из строки массив ячеек String[] cellsXml = rowXml.Split(columnDelimiters, StringSplitOptions.None); int j = 0; while (j < cellsXml.Length) { // Получить ячейку String cellXml = cellsXml[j]; // Убрать символ CRLF в конце строки cellXml = cellXml.TrimEnd(new char[] { '\n', '\r' }); // Добавить ноду ячейку в строку таблицы TableCell newTableCell = newTableRow.AppendChild(new TableCell()); // Вставить текст InsertText(cellXml, paragraphCellStyles[j], newTableCell); j++; } i++; } } /* Картинки */ if (sdtProperties.GetFirstChild <SdtContentPicture>() != null) { // Получить путь к файлу String imageFilePath = macroVarValue; // Получить расширение файла String extension = System.IO.Path.GetExtension(imageFilePath).ToLower(); ImagePartType imagePartType; switch (extension) { case "jpeg": imagePartType = ImagePartType.Jpeg; break; case "jpg": imagePartType = ImagePartType.Jpeg; break; case "png": imagePartType = ImagePartType.Png; break; case "bmp": imagePartType = ImagePartType.Bmp; break; case "gif": imagePartType = ImagePartType.Gif; break; default: imagePartType = ImagePartType.Jpeg; break; } ; // Добавить ImagePart в документ ImagePart imagePart = wdDoc.MainDocumentPart.AddImagePart(imagePartType); // Получить картинку using (FileStream stream = new FileStream(imageFilePath, FileMode.Open)) { imagePart.FeedData(stream); } // Вычислить width и height Bitmap img = new Bitmap(imageFilePath); var widthPx = img.Width; var heightPx = img.Height; var horzRezDpi = img.HorizontalResolution; var vertRezDpi = img.VerticalResolution; const int emusPerInch = 914400; const int emusPerCm = 360000; var widthEmus = (long)(widthPx / horzRezDpi * emusPerInch); var heightEmus = (long)(heightPx / vertRezDpi * emusPerInch); // Получить ID ImagePart string relationShipId = wdDoc.MainDocumentPart.GetIdOfPart(imagePart); Paragraph paragraph = sdtContentBlock.GetFirstChild <Paragraph>(); Run run = paragraph.GetFirstChild <Run>(); Drawing drawing = run.GetFirstChild <Drawing>(); Inline inline = drawing.GetFirstChild <Inline>(); Graphic graphic = inline.GetFirstChild <Graphic>(); GraphicData graphicData = graphic.GetFirstChild <GraphicData>(); Picture pic = graphicData.GetFirstChild <Picture>(); BlipFill blipFill = pic.GetFirstChild <BlipFill>(); Blip blip = blipFill.GetFirstChild <Blip>(); string prefix = "r"; string localName = "embed"; string namespaceUri = @"http://schemas.openxmlformats.org/officeDocument/2006/relationships"; OpenXmlAttribute oldEmbedAttribute = blip.GetAttribute("embed", namespaceUri); IList <OpenXmlAttribute> attributes = blip.GetAttributes(); if (oldEmbedAttribute != null) { attributes.Remove(oldEmbedAttribute); } // Удалить хз что, выявлено практическим путем blipFill.RemoveAllChildren <SourceRectangle>(); // Установить новую картинку blip.SetAttribute(new OpenXmlAttribute(prefix, localName, namespaceUri, relationShipId)); blip.SetAttribute(new OpenXmlAttribute("cstate", "", "print")); // Подогнать размеры Extent extent = inline.GetFirstChild <Extent>(); OpenXmlAttribute oldCxExtent = extent.GetAttribute("cx", ""); if (oldCxExtent != null) { var maxWidthEmus = long.Parse(oldCxExtent.Value); if (widthEmus > maxWidthEmus) { var ratio = (heightEmus * 1.0m) / widthEmus; widthEmus = maxWidthEmus; heightEmus = (long)(widthEmus * ratio); } extent.GetAttributes().Remove(oldCxExtent); } OpenXmlAttribute oldCyExtent = extent.GetAttribute("cy", ""); if (oldCyExtent != null) { extent.GetAttributes().Remove(oldCyExtent); } extent.SetAttribute(new OpenXmlAttribute("cx", "", widthEmus.ToString())); extent.SetAttribute(new OpenXmlAttribute("cy", "", heightEmus.ToString())); ShapeProperties shapeProperties = pic.GetFirstChild <ShapeProperties>(); Transform2D transform2D = shapeProperties.GetFirstChild <Transform2D>(); Extents extents = transform2D.GetFirstChild <Extents>(); OpenXmlAttribute oldCxExtents = extents.GetAttribute("cx", ""); if (oldCxExtents != null) { extents.GetAttributes().Remove(oldCxExtents); } OpenXmlAttribute oldCyExtents = extents.GetAttribute("cy", ""); if (oldCyExtents != null) { extents.GetAttributes().Remove(oldCyExtents); } extents.SetAttribute(new OpenXmlAttribute("cx", "", widthEmus.ToString())); extents.SetAttribute(new OpenXmlAttribute("cy", "", heightEmus.ToString())); // Удалить placeholder ShowingPlaceholder showingPlaceholder = sdtProperties.GetFirstChild <ShowingPlaceholder>(); if (showingPlaceholder != null) { sdtProperties.RemoveChild <ShowingPlaceholder>(showingPlaceholder); } } /* Повторяющийся раздел */ if (sdtProperties.GetFirstChild <SdtRepeatedSection>() != null) { // Представить repeatedSection как новый xml документ (сделать корнем) XmlDocument repeatedSectionXml = new XmlDocument(); repeatedSectionXml.LoadXml(macroVarValue); // Получить корневой элемент repeatedSection XmlElement rootRepeatedSectionXml = repeatedSectionXml.DocumentElement; // Получить количество repeatedSectionItem XmlNodeList repeatedSectionItems = rootRepeatedSectionXml.SelectNodes("repeatedSectionItem"); int repeatedItemCount = repeatedSectionItems.Count; Console.WriteLine("Количество repeatedSectionItem: " + repeatedItemCount); /* Блок клонирования ноды повтор. раздела до нужного количества */ for (int i = 0; i < repeatedItemCount; i++) { XmlElement macroListRepeatedSectionItem = rootRepeatedSectionXml.SelectSingleNode(String.Format(@"repeatedSectionItem[@id=""{0}""]", i)) as XmlElement; Console.WriteLine("Item " + i + ": " + macroListRepeatedSectionItem.OuterXml); SdtContentBlock sdtContentBlockRepeatedSectionItem = sdtContentBlock.Elements <SdtBlock>().Last <SdtBlock>().GetFirstChild <SdtContentBlock>(); Fill(sdtContentBlockRepeatedSectionItem, macroListRepeatedSectionItem, wdDoc); if (i + 1 < repeatedItemCount) { SdtBlock clonedRepeatedSectionItem = sdtContentBlock.GetFirstChild <SdtBlock>().Clone() as SdtBlock; sdtContentBlock.AppendChild <SdtBlock>(clonedRepeatedSectionItem); } } /**/ //Fill(sdtContentBlock, macroListRepeatedSection, wdDoc); } } Console.WriteLine(); } }
private async void Initialize() { // As of ArcGIS Enterprise 10.8.1, using utility network functionality requires a licensed user. The following login for the sample server is licensed to perform utility network operations. AuthenticationManager.Current.ChallengeHandler = new ChallengeHandler(async(info) => { try { // WARNING: Never hardcode login information in a production application. This is done solely for the sake of the sample. string sampleServer7User = "******"; string sampleServer7Pass = "******"; return(await AuthenticationManager.Current.GenerateCredentialAsync(info.ServiceUri, sampleServer7User, sampleServer7Pass)); } catch (Exception ex) { System.Diagnostics.Debug.WriteLine(ex.Message); return(null); } }); try { // Disable the UI. FilterOptions.Visibility = Visibility.Collapsed; // Create and load the utility network. _utilityNetwork = await UtilityNetwork.CreateAsync(new Uri(FeatureServiceUrl)); // Create a map with layers in this utility network. MyMapView.Map = new Map(BasemapStyle.ArcGISStreetsNight); MyMapView.Map.OperationalLayers.Add(new FeatureLayer(new Uri($"{FeatureServiceUrl}/{LineLayerId}"))); MyMapView.Map.OperationalLayers.Add(new FeatureLayer(new Uri($"{FeatureServiceUrl}/{DeviceLayerId}"))); // Get a trace configuration from a tier. UtilityDomainNetwork domainNetwork = _utilityNetwork.Definition.GetDomainNetwork(DomainNetworkName) ?? throw new ArgumentException(DomainNetworkName); UtilityTier tier = domainNetwork.GetTier(TierName) ?? throw new ArgumentException(TierName); _configuration = tier.TraceConfiguration; // Create a trace filter. _configuration.Filter = new UtilityTraceFilter(); // Get a default starting location. UtilityNetworkSource networkSource = _utilityNetwork.Definition.GetNetworkSource(NetworkSourceName) ?? throw new ArgumentException(NetworkSourceName); UtilityAssetGroup assetGroup = networkSource.GetAssetGroup(AssetGroupName) ?? throw new ArgumentException(AssetGroupName); UtilityAssetType assetType = assetGroup.GetAssetType(AssetTypeName) ?? throw new ArgumentException(AssetTypeName); Guid globalId = Guid.Parse(GlobalId); _startingLocation = _utilityNetwork.CreateElement(assetType, globalId); // Create a graphics overlay. GraphicsOverlay overlay = new GraphicsOverlay(); MyMapView.GraphicsOverlays.Add(overlay); // Display starting location. IEnumerable <ArcGISFeature> elementFeatures = await _utilityNetwork.GetFeaturesForElementsAsync(new List <UtilityElement> { _startingLocation }); MapPoint startingLocationGeometry = elementFeatures.FirstOrDefault().Geometry as MapPoint; Symbol symbol = new SimpleMarkerSymbol(SimpleMarkerSymbolStyle.Cross, System.Drawing.Color.LimeGreen, 25d); Graphic graphic = new Graphic(startingLocationGeometry, symbol); overlay.Graphics.Add(graphic); // Set the starting viewpoint. await MyMapView.SetViewpointAsync(new Viewpoint(startingLocationGeometry, 3000)); // Build the choice list for categories populated with the `Name` property of each `UtilityCategory` in the `UtilityNetworkDefinition`. Categories.ItemsSource = _utilityNetwork.Definition.Categories; Categories.SelectedItem = _utilityNetwork.Definition.Categories.First(); // Enable the UI. FilterOptions.Visibility = Visibility.Visible; } catch (Exception ex) { await new MessageDialog(ex.Message, ex.GetType().Name).ShowAsync(); } finally { LoadingBar.Visibility = Visibility.Collapsed; } }