public static bool[,] Raster2Mat1(IRasterLayer rasterlayer) { IRaster raster = rasterlayer.Raster; IRaster2 raster2 = raster as IRaster2; bool[,] mat = new bool[rasterlayer.RowCount, rasterlayer.ColumnCount]; for (int i = 0; i < rasterlayer.RowCount; i++) { for (int j = 0; j < rasterlayer.ColumnCount; j++) { object value = raster2.GetPixelValue(0, j, i); if (value == null) { mat[i, j] = false; } else { bool x = Convert.ToBoolean(raster2.GetPixelValue(0, j, i)); mat[i, j] = x; } } } return(mat); }
private void axMapControl1_OnMouseDown(object sender, ESRI.ArcGIS.Controls.IMapControlEvents2_OnMouseDownEvent e) { xMap = e.mapX; yMap = e.mapY; string selectedraster = "slope"; if (listBox1.SelectedItem == null) { selectedraster = selectedraster + "512";//defaut finest raster } else { selectedraster = selectedraster + Math.Pow(2, double.Parse(listBox1.SelectedItem.ToString())).ToString(); } IRaster2 ras2 = MapXY2RowCol(xMap, yMap, selectedraster);//FInest Resolution Ratername if (ras2.GetPixelValue(0, col, row) == null) { MessageBox.Show("Please open map"); return; } float pixelvalue = ras2.GetPixelValue(0, col, row); if (e.button == 2) { MessageBox.Show("x:" + xMap + " y:" + yMap + "\n" + "row:" + row + " col:" + col + "value:" + pixelvalue); } }
public static double GetZValue(this IRaster raster, IPoint point) { IPoint testPoint = new PointClass() { X = point.X, Y = point.Y, SpatialReference = point.SpatialReference }; testPoint.Project(((IRasterProps)raster).SpatialReference); IRaster2 raster2 = (IRaster2)raster; try { //Get the column and row by giving x,y coordinates in a map space. int col = raster2.ToPixelColumn(testPoint.X); int row = raster2.ToPixelRow(testPoint.Y); //Get the value at a given band. var pixel = raster2.GetPixelValue(0, col, row); return(pixel != null ? (double)Convert.ChangeType(pixel, typeof(double)) : double.NaN); } catch { return(double.NaN); } }
public void LoadDEM(string rastername, ref Dictionary <int, float> resultdic) // 加ref防止null rasterdic { resultdic = new Dictionary <int, float>(); rasterkey = new List <int>(); rastervalue = new List <float>(); IWorkspaceFactory pWSF = new RasterWorkspaceFactory(); string fileName = @"D:\study\ao\MortonCode\slopedata"; IRasterWorkspace pRWS = pWSF.OpenFromFile(fileName, 0) as IRasterWorkspace; if (pRWS == null) { MessageBox.Show("Could not open raster workspace"); return; } IRasterDataset rasterData = pRWS.OpenRasterDataset(rastername); if (rasterData == null) { MessageBox.Show("Could not open raster dataset"); return; } IRaster2 raster = rasterData.CreateDefaultRaster() as IRaster2; IRasterLayer rasterlayer = new RasterLayerClass(); rasterlayer.CreateFromDataset(rasterData); int col; int row; float pixelValue; int maxrow = rasterlayer.RowCount; int maxcol = rasterlayer.ColumnCount; for (row = 0; row < maxrow; row++) { for (col = 0; col < maxcol; col++) { rasterkey.Add(GetMorton(row, col, maxrow)); pixelValue = raster.GetPixelValue(0, col, row); rastervalue.Add(pixelValue); } } for (int i = 0; i < maxcol * maxrow; i++) { resultdic.Add(rasterkey[i], rastervalue[i]); } //foreach (KeyValuePair<int, double> kvp in rasterdic1) //{ // MessageBox.Show("MD: " + kvp.Key + " Slope: " + kvp.Value); //} MessageBox.Show("Number of pixels: " + resultdic.Count); //rasterdic1_sort = (from entry in rasterdic1 //orderby entry.Key ascending //select entry).ToDictionary(pair => pair.Key, pair => pair.Value); //MessageBox.Show("Number of sorted pixel: " + rasterdic1_sort.Count); //MessageBox.Show(rasterdic1_sort.Keys.ToString()); }
/// <summary> /// return value of pixel /// </summary> /// <param name="raster">object raster</param> /// <param name="x">coordinate x</param> /// <param name="y">coordinate y</param> /// <returns>value of pixel</returns> public static double IdentifyPixelValue(IRaster2 raster, double x, double y) { // Get the column and row by giving x,y coordinates in a map space. int col = raster.ToPixelColumn(x); int row = raster.ToPixelRow(y); // Get the value at a given band. object o = raster.GetPixelValue(0, col, row); return((o == null) ? double.NaN : Convert.ToDouble(o)); }
public static double GetH(IPoint point) { IRaster raster = GetDEM(); IRaster2 raster2 = raster as IRaster2; int row = 0; int col = 0; raster2.MapToPixel(point.X, point.Y, out col, out row); object obj = raster2.GetPixelValue(0, col, row); double height = Convert.ToDouble(obj.ToString()); return(height); }
//获取某行列栅格单元的值 public static object GetPixelValue(IRasterLayer pRasterLayer, int iBand, int column, int row) { try { IRaster pRaster = pRasterLayer.Raster; IRaster2 pRaster2 = pRaster as IRaster2; return(pRaster2.GetPixelValue(iBand, column, row)); } catch (Exception ex) { MessageBox.Show(ex.Message + "\n" + ex.ToString(), "异常"); return(null); } }
private void button6_Click(object sender, EventArgs e) { xMap = 474693.1; yMap = 4474435.1; //Get the column and row by giving x,y coordinates in a map space. //col = raster.ToPixelColumn(xMap); //row = raster.ToPixelRow(yMap); IRaster2 ras = MapXY2RowCol(xMap, yMap, "slope8x8"); MessageBox.Show("Row:" + row.ToString() + " Col:" + col.ToString()); //Get the value at a given band. double pixelValue = ras.GetPixelValue(0, col, row); MessageBox.Show("Row:" + row.ToString() + " Col:" + col.ToString() + " value: " + pixelValue.ToString()); }
public static int[,] Raster2Mat2(IRasterLayer rasterlayer) { IRaster raster = rasterlayer.Raster; IRaster2 raster2 = raster as IRaster2; int[,] mat = new int[rasterlayer.RowCount, rasterlayer.ColumnCount]; for (int i = 0; i < rasterlayer.RowCount; i++) { for (int j = 0; j < rasterlayer.ColumnCount; j++) { object value = raster2.GetPixelValue(0, j, i); if (value == null) { mat[i, j] = 0; } else { mat[i, j] = Convert.ToInt32(raster2.GetPixelValue(0, j, i)); } } } return(mat); }
/// <summary> /// Occurs when this tool is clicked /// </summary> /// public void GetPixValue(IRasterLayer pRasterlayer, IPoint pt, out object value) { value = new object(); IRaster pRaster = pRasterlayer.Raster; IRasterProps rasterProps = (IRasterProps)pRaster; IEnvelope extent = rasterProps.Extent; IRelationalOperator pRO = pt as IRelationalOperator; if (!pRO.Within(extent)) { return; } IRaster2 pRaster2 = pRaster as IRaster2; int row = pRaster2.ToPixelRow(pt.Y); int col = pRaster2.ToPixelColumn(pt.X); value = pRaster2.GetPixelValue(0, col, row); }
public override void OnMouseDown(int Button, int Shift, int X, int Y) { // TODO: Add ToolAddCraterOnTIN.OnMouseDown implementation if (pTinLayer != null) { ITin pTin = pTinLayer.Dataset; ISurface pSurface = ((ITinAdvanced)pTin).Surface; IMapControl2 pMapCtr = (((IToolbarControl)m_hookHelper.Hook).Buddy) as IMapControl2; //在mapctr操作 if (pMapCtr != null) { IPoint mapPoint = pMapCtr.ToMapPoint(X, Y); IZAware za = mapPoint as IZAware; za.ZAware = true; double zVal; zVal = pSurface.GetElevation(mapPoint); if (double.IsNaN(zVal)) { MessageBox.Show("获取模型的高度失败!"); return; } if (m_listModels.Count == 0) { MessageBox.Show("请先生成模型!"); return; } mapPoint.Z = zVal; try { //IMultiPatch pMP = new MultiPatchClass(); IFeatureClass pFC = pFeatureLayer.FeatureClass; IFeature pF = pFC.CreateFeature(); IImport3DFile pI3D = new Import3DFileClass(); pI3D.CreateFromFile(m_listModels[m_listModels.Count - 1]); IMultiPatch pMP = pI3D.Geometry as IMultiPatch; ITransform3D pT3D = pMP as ITransform3D; pT3D.Move3D(mapPoint.X, mapPoint.Y, mapPoint.Z); pF.Shape = pMP as IGeometry; pF.Store(); if (pMapCtr != null) { pMapCtr.ActiveView.PartialRefresh(esriViewDrawPhase.esriViewGeography, null, null); } } catch (SystemException e) { MessageBox.Show(e.Message); } //IMultiPatch pMP = new MultiPatchClass(); //for (int i = 0; i < 5; i++) //{ // IFeature pF = pFC.CreateFeature(); // IImport3DFile pI3D = new Import3DFileClass(); // pI3D.CreateFromFile(@"C:\Users\Administrator\Desktop\sampleAnalysis\1002.3ds"); // IMultiPatch pMP = pI3D.Geometry as IMultiPatch; // // ITransform3D pT3D = pMP as ITransform3D; // pF.Shape = pMP as IGeometry; // ITransform3D pT3D = pF.Shape as ITransform3D; // pT3D.Move3D(5293 + 1600, -20427 , 800 + i*400); // // pF.Shape = pI3D.Geometry; } } if (pRasterLayer != null) { //ITin pTin = pTinLayer.Dataset; //ISurface pSurface = ((ITinAdvanced)pTin).Surface; IMapControl2 pMapCtr = (((IToolbarControl)m_hookHelper.Hook).Buddy) as IMapControl2; //在mapctr操作 if (pMapCtr != null) { IPoint mapPoint = pMapCtr.ToMapPoint(X, Y); //添加手工编辑窗口 FrmManualSetModelPara pManualSetPara = null; if (m_pModel == null) { Pt2d ptCurrent = new Pt2d(); ptCurrent.X = mapPoint.X; ptCurrent.Y = mapPoint.Y; pManualSetPara = new FrmManualSetModelPara(ptCurrent, "Crater"); } else { m_pModel.x = mapPoint.X; m_pModel.y = mapPoint.Y; pManualSetPara = new FrmManualSetModelPara(m_pModel); } //FrmManualSetModelPara pManualSetPara = new FrmManualSetModelPara(ptCurrent, "Crater"); if (pManualSetPara.ShowDialog() == DialogResult.OK) { if (m_pModel == null) { m_pModel = new Model(); } bool bFlag = m_pModel.compareModelPara(pManualSetPara.m_pModel); if (!bFlag) //模型参数已经被修改,需要重新生成新的模型文件 { m_pModel.copyFromModel(pManualSetPara.m_pModel); //根据设置的参数生成相应的模型 TriType triType = TriType.TriForward; LibModelGen.MappingType mappingType = LibModelGen.MappingType.Flat; String szModelOutputFilename = System.IO.Path.GetTempFileName(); szModelOutputFilename = szModelOutputFilename.Substring(0, szModelOutputFilename.LastIndexOf('.')) + ".3ds"; ModelBase crater = new CraterGen(m_pModel.dbSize, m_pModel.dbDepth); crater.OutputFilename = szModelOutputFilename; crater.triype = triType; crater.mappingType = mappingType; //将撞击坑模型添加到相应图层 if (crater.generate()) { m_listModels.Add(szModelOutputFilename); } } //保存当前添加的模型参数 Model pTmpModel = new Model(); pTmpModel.copyFromModel(pManualSetPara.m_pModel); m_manualAddModels.Add(pTmpModel); } else { return; } IZAware za = mapPoint as IZAware; za.ZAware = true; double zVal; IRaster2 pRaster2 = pRasterLayer.Raster as IRaster2; int col, row; pRaster2.MapToPixel(mapPoint.X, mapPoint.Y, out col, out row); zVal = Convert.ToDouble(pRaster2.GetPixelValue(0, col, row)); if (double.IsNaN(zVal)) { MessageBox.Show("获取模型的高度失败!"); return; } if (m_listModels.Count == 0) { MessageBox.Show("请先生成模型!"); return; } mapPoint.Z = zVal; IFeature pfeature = null; try { //IMultiPatch pMP = new MultiPatchClass(); IFeatureClass pFC = pFeatureLayer.FeatureClass; IFeature pF = pFC.CreateFeature(); IImport3DFile pI3D = new Import3DFileClass(); pI3D.CreateFromFile(m_listModels[m_listModels.Count - 1]); IMultiPatch pMP = pI3D.Geometry as IMultiPatch; ITransform3D pT3D = pMP as ITransform3D; // pT3D.Move3D(mapPoint.X, mapPoint.Y, mapPoint.Z); pT3D.Move3D(pManualSetPara.m_pModel.x, pManualSetPara.m_pModel.y, mapPoint.Z); //IRasterProps pRasterProps = pRasterLayer.Raster as IRasterProps; //double xmax = pRasterProps.Extent.XMax; //double xmin = pRasterProps.Extent.XMin; //double ymax = pRasterProps.Extent.YMax; //double ymin = pRasterProps.Extent.YMin; ////生成地形的地理范围 //double dbGeoRangeX = xmax - xmin; //double dbGeoRangeY = ymax - ymin; //double dbModelRangeX = pMP.Envelope.Width; //double dbModelRangeY = pMP.Envelope.Height; //double dbModelRangeZ = pMP.Envelope.ZMax - pMP.Envelope.ZMin; //根据地形大小改变撞击坑大小 //double dbRandomSize = Math.Min(dbGeoRangeX, dbGeoRangeY) * (0.15); //[0.03 0.06] //double dbRandomSize = pRasterProps.MeanCellSize().X * 300; //double dbScale = pManualSetPara.m_pModel.dbSize;// / Math.Max(dbModelRangeX, dbModelRangeY); //pT3D.Scale3D(mapPoint, dbScale, dbScale, dbScale); pF.Shape = pMP as IGeometry; pfeature = pF as IFeature; pF.Store(); if (pMapCtr != null) { pMapCtr.ActiveView.PartialRefresh(esriViewDrawPhase.esriViewGeography, null, null); } } catch (SystemException e) { if (e.Message == "The spatial index grid size is invalid.") { IFeatureClassLoad pFCL = pFeatureLayer.FeatureClass as IFeatureClassLoad; pFCL.LoadOnlyMode = true; pfeature.Store(); pFCL.LoadOnlyMode = false; } else { MessageBox.Show(e.Message); } } } } }
/// <summary> /// 计算碳储量---逐个像元读取(暂时弃用) /// </summary> public Boolean Cal_carbonStorage() { double sumDensity = 0; double value = 0; IRasterLayer rasLyr = new RasterLayerClass(); //int debugx = 0; //int debugY = 0; try { rasLyr.CreateFromFilePath(carbonDensity); IRaster2 raster = rasLyr.Raster as IRaster2; //普通循环计算碳密度像元和 //for (int i = 0; i < rasLyr.ColumnCount; i++) //{ // for (int j = 0; j < rasLyr.RowCount; j++) // { // if (double.TryParse(raster.GetPixelValue(0, i, j).ToString(), out value)) // sumDensity += value; // } //} //控制并行度 ParallelOptions parallelOptions = new ParallelOptions { MaxDegreeOfParallelism = Environment.ProcessorCount * 2 }; Stopwatch stopwatch = new Stopwatch(); stopwatch.Start(); //并行循环 Parallel.For(0, rasLyr.ColumnCount, col => { Parallel.For(0, rasLyr.RowCount, row => { object o = raster.GetPixelValue(0, col, row); if (o != null) { if (double.TryParse(o.ToString(), out value)) { sumDensity += value; //Console.WriteLine(sumDensity); } } }); //for (int row = 0; row < rasLyr.RowCount; row++) //{ // object o = raster.GetPixelValue(0, col, row); // if (o != null) // { // if (double.TryParse(o.ToString(), out value)) // sumDensity += value; // } //} }); stopwatch.Stop(); TimeSpan timeSpan = stopwatch.Elapsed; Console.WriteLine("碳密度加和计算用时:" + timeSpan.TotalSeconds + "s 循环大小:" + rasLyr.ColumnCount + "," + rasLyr.RowCount); //计算碳储量 double Storage = sumDensity * forestArea; //写出结果到文本 //TxtOP.WriteTxt(carbonStorage, Storage); return(true); } catch (Exception ex) { XtraMessageBox.Show("计算森林碳储量失败!\r\n" + ex.Message); return(false); } finally { if (rasLyr != null) { Marshal.ReleaseComObject(rasLyr); } } }
/// <summary> /// 计算植被面积---逐像元读取(暂时弃用) /// </summary> /// <returns>System.Double.</returns> public Boolean Cal_forestCover() { int forestCount = 0; IRasterLayer rasLyr = new RasterLayerClass(); try { rasLyr.CreateFromFilePath(landCover); IRaster2 raster = rasLyr.Raster as IRaster2; //获取像元大小 IRasterProps rasterProps = (IRasterProps)raster; double cellSize = rasterProps.MeanCellSize().X; //控制并行度 //ParallelOptions parallelOptions = new ParallelOptions { MaxDegreeOfParallelism = Environment.ProcessorCount*2 }; Stopwatch stopwatch = new Stopwatch(); stopwatch.Start(); //并行循环 Parallel.For(0, rasLyr.ColumnCount, col => { Parallel.For(0, rasLyr.RowCount, row => { object o = raster.GetPixelValue(0, col, row); if (o != null) { if (int.Parse(o.ToString()) == 4) { forestCount++; //Console.WriteLine(forestCount); } } }); }); ////普通循环计算林地像元个数 //for (int i = 0; i < rasLyr.ColumnCount; i++) // for (int j = 0; j < rasLyr.RowCount; j++) // { // object o = raster.GetPixelValue(0, i, j); // if (o != null) // { // if (int.Parse(o.ToString()) == 4) // { // forestCount++; // } // } // } stopwatch.Stop(); TimeSpan timeSpan = stopwatch.Elapsed; Console.WriteLine("林地像元计算用时:" + timeSpan.TotalSeconds + "s 循环大小:" + rasLyr.ColumnCount + "," + rasLyr.RowCount); //计算林地像元面积 forestArea = forestCount * cellSize * cellSize / 100; return(true); } catch (Exception ex) { XtraMessageBox.Show("计算森林面积失败!\r\n" + ex.Message); return(false); } finally { if (rasLyr != null) { Marshal.ReleaseComObject(rasLyr); } } }
private static Dictionary <string, double[][]> getDictionaryValues(ESRI.ArcGIS.Geodatabase.IFeatureClass pointFtr, ESRI.ArcGIS.Geodatabase.IField[] fldsToSummarize, IFunctionRasterDataset strataRaster, geoDatabaseUtility geoUtil, rasterUtil rsUtil) { IRaster2 rs2 = (IRaster2)rsUtil.createRaster(strataRaster); int[] ptfldIndex = new int[fldsToSummarize.Length]; for (int i = 0; i < ptfldIndex.Length; i++) { ptfldIndex[i] = pointFtr.FindField(fldsToSummarize[i].Name); } Dictionary <string, double[][]> outDic = new Dictionary <string, double[][]>(); IFeatureCursor sCur = pointFtr.Search(null, true); IFeature sFtr = sCur.NextFeature(); while (sFtr != null) { IGeometry geo = sFtr.Shape; IPoint pnt = (IPoint)geo; int clm, rw; rs2.MapToPixel(pnt.X, pnt.Y, out clm, out rw); object strataVlObj = rs2.GetPixelValue(0, clm, rw); if (strataVlObj != null) { string strataVl = strataVlObj.ToString(); double[][] vlArr; if (outDic.TryGetValue(strataVl, out vlArr)) { for (int i = 0; i < ptfldIndex.Length; i++) { object vlObj = sFtr.get_Value(ptfldIndex[i]); if (vlObj != null) { double vl = System.Convert.ToDouble(vlObj); vlArr[i][0] += vl; vlArr[i][1] += (vl * vl); vlArr[i][2] += 1; } } } else { vlArr = new double[fldsToSummarize.Length][]; for (int i = 0; i < ptfldIndex.Length; i++) { double[] vlSumArr = new double[3]; object vlObj = sFtr.get_Value(ptfldIndex[i]); if (vlObj != null && !System.Convert.IsDBNull(vlObj)) { double vl = System.Convert.ToDouble(vlObj); vlSumArr[0] = vl; vlSumArr[1] = (vl * vl); vlSumArr[2] = 1; } vlArr[i] = vlSumArr; } outDic[strataVl] = vlArr; } } sFtr = sCur.NextFeature(); } System.Runtime.InteropServices.Marshal.ReleaseComObject(sCur); return(outDic); }
public bool SetRegionToNoDataValue() { try { if (m_pSrcRaster == null || m_pClipPolygon == null || double.IsNaN(m_dbNoDataValue)) { return(false); } IGeoDataset pSrcGeoDataset = m_pSrcRaster as IGeoDataset; IExtractionOp pRasterExtractionOp = new RasterExtractionOpClass(); IRasterProps pSrcRasterProps = m_pSrcRaster as IRasterProps; double dbCellSize = (pSrcRasterProps.MeanCellSize().X + pSrcRasterProps.MeanCellSize().Y) / 2; //设置范围和分辨率 IRasterAnalysisEnvironment pRasterAnalysisEnv = pRasterExtractionOp as IRasterAnalysisEnvironment; pRasterAnalysisEnv.SetCellSize(esriRasterEnvSettingEnum.esriRasterEnvValue, dbCellSize); pRasterAnalysisEnv.SetExtent(esriRasterEnvSettingEnum.esriRasterEnvValue, m_pClipPolygon.Envelope, Type.Missing); //pRasterAnalysisEnv.OutSpatialReference = (m_pSrcRaster as IRasterProps).SpatialReference; //保留区域外的值,区域内的设置为原始栅格的无效值 IGeoDataset pDstGeoDataset = pRasterExtractionOp.Rectangle(pSrcGeoDataset, m_pClipPolygon.Envelope, true); //逐点判断像素是否在区域内,在区域内则改变为设置值,否则不变 IRelationalOperator pRelationalOp = m_pClipPolygon as IRelationalOperator; if (pDstGeoDataset is IRaster) { //得到原始栅格的对象,用于修改 IRaster2 pSrcRaster2 = m_pSrcRaster as IRaster2; IRasterDataset2 pSrcRasterDataset2 = pSrcRaster2.RasterDataset as IRasterDataset2; IRaster pTmpRaster = pSrcRasterDataset2.CreateFullRaster(); IRasterEdit pSrcEdit = pTmpRaster as IRasterEdit; //得到图层NoDataValue IRasterProps rasterProps = pSrcRaster2 as IRasterProps; double noData = ClsGDBDataCommon.getNoDataValue(rasterProps.NoDataValue); //得到输出的栅格 IRaster2 pDstRaster2 = pDstGeoDataset as IRaster2; IRasterProps pDstRasterProps = pDstRaster2 as IRasterProps; IRasterCursor pDstRasterCursor = pDstRaster2.CreateCursorEx(null); //pDstRasterCursor.Reset(); do { //得到当前处理的块 IPixelBlock3 pixelBlock3 = pDstRasterCursor.PixelBlock as IPixelBlock3; int nWidth = pixelBlock3.Width; int nHeight = pixelBlock3.Height; IPnt ptLeftTop = pDstRasterCursor.TopLeft; //block值转数组时,NoData转换时有时为NoData,有时为栅格中的最小值 System.Array array = pixelBlock3.get_PixelData(0) as System.Array; //逐点判断: 判断像素是否在区域内,在区域内则改变为设置值,否则不变 for (int i = 0; i < nWidth; i++) { for (int j = 0; j < nHeight; j++) { double dbX = double.NaN, dbY = double.NaN; //得到当前像素点的地图坐标 int nCurrentX = Convert.ToInt32(ptLeftTop.X + i); int nCurrentY = Convert.ToInt32(ptLeftTop.Y + j); pDstRaster2.PixelToMap(nCurrentX, nCurrentY, out dbX, out dbY); IPoint ptInMap = new PointClass(); ptInMap.X = dbX; ptInMap.Y = dbY; //判断是否在区域内 bool bFlag = pRelationalOp.Contains(ptInMap as IGeometry); if (bFlag) //在当前区域内 { object oValidValue = getValidType(pDstRasterProps, m_dbNoDataValue); array.SetValue(oValidValue, i, j); } else { double v = Convert.ToDouble(array.GetValue(i, j)); if (v == 0 || v < -3.4e15 || v > 3.4e15) //if (v == 0 || Math.Abs(v -noData) <1e18) { int col, row; pSrcRaster2.MapToPixel(dbX, dbY, out col, out row); //表示getpixelvalue为null表示nodata object obj = pSrcRaster2.GetPixelValue(0, col, row); if (obj == null) { object oValidValue = getValidType(pDstRasterProps, m_dbNoDataValue); array.SetValue(oValidValue, i, j); } else { array.SetValue(obj, i, j); } } } } } pixelBlock3.set_PixelData(0, array); //得到当前区域块在原图中的左上角像素坐标, 直接修改原栅格的数据 int nPixelLeftX = -1, nPixelLeftY = -1; double dbMapLeftTopX = double.NaN, dbMapLeftTopY = double.NaN; pDstRaster2.PixelToMap(Convert.ToInt32(ptLeftTop.X), Convert.ToInt32(ptLeftTop.Y), out dbMapLeftTopX, out dbMapLeftTopY); //得到当前块左上角的地理坐标 pSrcRaster2.MapToPixel(dbMapLeftTopX, dbMapLeftTopY, out nPixelLeftX, out nPixelLeftY); IPnt ptPixelLeftTop = new PntClass(); ptPixelLeftTop.SetCoords(nPixelLeftX, nPixelLeftY); if (pSrcEdit.CanEdit()) { pSrcEdit.Write(ptPixelLeftTop, pixelBlock3 as IPixelBlock); //pSrcEdit.Refresh(); } else { return(false); } } while (pDstRasterCursor.Next() == true); //更新 pSrcEdit.Refresh(); } else { return(false); } return(true); } catch (System.Exception ex) { return(false); } }
public override void OnMouseDown(int Button, int Shift, int X, int Y) { if (Button == 1) { List <ILayer> layers = EngineAPI.GetLayers(this.m_hookHelper.FocusMap, "{6CA416B1-E160-11D2-9F4E-00C04F6BC78E}", null); if (layers.Count == 0) { IdentifyManager.instance.FrmIdentify.Close(); IdentifyManager.instance.FrmIdentify = null; EnviVars.instance.MapControl.CurrentTool = null; EnviVars.instance.MapControl.MousePointer = esriControlsMousePointer.esriPointerDefault; } else { foreach (ILayer current in layers) { IIdentify identify = current as IIdentify; IPoint point = this.m_hookHelper.ActiveView.ScreenDisplay.DisplayTransformation.ToMapPoint(X, Y); IArray array = identify.Identify(point); if (array != null && array.Count != 0) { IdentifyManager.instance.FrmIdentify.treeList1.ClearNodes(); IIdentifyObj identifyObj = array.get_Element(0) as IIdentifyObj; identifyObj.Flash(this.m_hookHelper.ActiveView.ScreenDisplay); TreeListNode treeListNode = IdentifyManager.instance.FrmIdentify.treeList1.AppendNode(new object[] { identifyObj.Layer.Name }, 0, identifyObj); DataColumn column = new DataColumn("字段", typeof(string)); DataColumn column2 = new DataColumn("值", typeof(string)); DataTable dataTable = new DataTable(); dataTable.Columns.Add(column); dataTable.Columns.Add(column2); if (current is IFeatureLayer) { IFeature feature = (identifyObj as IRowIdentifyObject).Row as IFeature; TreeListNode treeListNode2 = IdentifyManager.instance.FrmIdentify.treeList1.AppendNode(new object[] { feature.OID.ToString() }, treeListNode); int num = feature.Fields.FindField((current as IFeatureLayer).FeatureClass.ShapeFieldName); for (int i = 0; i < feature.Fields.FieldCount; i++) { if (num != i) { DataRow dataRow = dataTable.NewRow(); dataRow["字段"] = feature.Fields.get_Field(i).AliasName; dataRow["值"] = feature.get_Value(i).ToString(); dataTable.Rows.Add(dataRow); } } treeListNode2.Tag = dataTable; } else if (current is IRasterLayer) { IRasterLayer rasterLayer = current as IRasterLayer; IRaster2 raster = rasterLayer.Raster as IRaster2; int num2 = raster.ToPixelRow(point.Y); int num3 = raster.ToPixelColumn(point.X); double num4 = CommonAPI.ConvertToDouble(raster.GetPixelValue(0, num3, num2)); this.AddRow(dataTable, "像素值", num4); this.AddRow(dataTable, "行号", num2); this.AddRow(dataTable, "列号", num3); IRasterIdentifyObj rasterIdentifyObj = array.get_Element(0) as IRasterIdentifyObj; if (rasterLayer.BandCount != 1) { Regex regex = new Regex("\\d{2,3}"); MatchCollection matchCollection = regex.Matches(rasterIdentifyObj.MapTip); if (matchCollection.Count == 3) { this.AddRow(dataTable, "R", matchCollection[0].Value); this.AddRow(dataTable, "G", matchCollection[1].Value); this.AddRow(dataTable, "B", matchCollection[2].Value); } } IdentifyManager.instance.FrmIdentify.treeList1.AppendNode(new object[] { rasterIdentifyObj.Name }, treeListNode, dataTable); } IdentifyManager.instance.FrmIdentify.UpdateStatusText(string.Format("X:{0:0.000 },Y:{1:0.000}", point.X, point.Y)); IdentifyManager.instance.FrmIdentify.treeList1.ExpandAll(); if (treeListNode.Nodes.Count > 0) { IdentifyManager.instance.FrmIdentify.treeList1.FocusedNode = treeListNode.Nodes[0]; } IdentifyManager.instance.FrmIdentify.Show(); break; } IdentifyManager.instance.FrmIdentify.Close(); IdentifyManager.instance.FrmIdentify = null; } } } }
public override void OnMouseDown(int Button, int Shift, int X, int Y) { // TODO: Add ToolAddStone.OnMouseDown implementation if (pTinLayer != null) { ITin pTin = pTinLayer.Dataset; ISurface pSurface = ((ITinAdvanced)pTin).Surface; IMapControl2 pMapCtr = (((IToolbarControl)m_hookHelper.Hook).Buddy) as IMapControl2; //在mapctr操作 if (pMapCtr != null) { IPoint mapPoint = pMapCtr.ToMapPoint(X, Y); IZAware za = mapPoint as IZAware; za.ZAware = true; double zVal; zVal = pSurface.GetElevation(mapPoint); if (double.IsNaN(zVal)) { MessageBox.Show("获取模型的高度失败!"); return; } if (m_listModels.Count == 0) { MessageBox.Show("请先生成模型!"); return; } mapPoint.Z = zVal; IFeature pfeature = null; try { //IMultiPatch pMP = new MultiPatchClass(); IFeatureClass pFC = pFeatureLayer.FeatureClass; IFeature pF = pFC.CreateFeature(); IImport3DFile pI3D = new Import3DFileClass(); pI3D.CreateFromFile(m_listModels[m_listModels.Count - 1]); IMultiPatch pMP = pI3D.Geometry as IMultiPatch; ITransform3D pT3D = pMP as ITransform3D; pT3D.Move3D(mapPoint.X, mapPoint.Y, mapPoint.Z); pF.Shape = pMP as IGeometry; pfeature = pF as IFeature; pF.Store(); if (pMapCtr != null) { pMapCtr.ActiveView.PartialRefresh(esriViewDrawPhase.esriViewGeography, null, null); } } catch (SystemException e) { if (e.Message == "The spatial index grid size is invalid.") { IFeatureClassLoad pFCL = pFeatureLayer.FeatureClass as IFeatureClassLoad; pFCL.LoadOnlyMode = true; pfeature.Store(); pFCL.LoadOnlyMode = false; } else { MessageBox.Show(e.Message); } } //IMultiPatch pMP = new MultiPatchClass(); //for (int i = 0; i < 5; i++) //{ // IFeature pF = pFC.CreateFeature(); // IImport3DFile pI3D = new Import3DFileClass(); // pI3D.CreateFromFile(@"C:\Users\Administrator\Desktop\sampleAnalysis\1002.3ds"); // IMultiPatch pMP = pI3D.Geometry as IMultiPatch; // // ITransform3D pT3D = pMP as ITransform3D; // pF.Shape = pMP as IGeometry; // ITransform3D pT3D = pF.Shape as ITransform3D; // pT3D.Move3D(5293 + 1600, -20427 , 800 + i*400); // // pF.Shape = pI3D.Geometry; } } if (pRasterLayer != null) { //ITin pTin = pTinLayer.Dataset; //ISurface pSurface = ((ITinAdvanced)pTin).Surface; IMapControl2 pMapCtr = (((IToolbarControl)m_hookHelper.Hook).Buddy) as IMapControl2; //在mapctr操作 if (pMapCtr != null) { IPoint mapPoint = pMapCtr.ToMapPoint(X, Y); //添加手工编辑窗口 FrmManualSetModelPara pManualSetPara = null; if (m_pModel == null) { Pt2d ptCurrent = new Pt2d(); ptCurrent.X = mapPoint.X; ptCurrent.Y = mapPoint.Y; pManualSetPara = new FrmManualSetModelPara(ptCurrent, "Rock"); } else { m_pModel.x = mapPoint.X; m_pModel.y = mapPoint.Y; pManualSetPara = new FrmManualSetModelPara(m_pModel); } if (pManualSetPara.ShowDialog() == DialogResult.OK) { if (m_pModel == null) { m_pModel = new Model(); } //bool bFlag = m_pModel.compareModelPara(pManualSetPara.m_pModel); //if (!bFlag)//模型参数已经被修改,需要重新生成新的模型文件 //{ // m_pModel.copyFromModel(pManualSetPara.m_pModel); // //获得当前文件路径下的石头模型文件,并随机获得石块模型 // String szAppPathName = GetParentPathofExe() + @"Resource\RockModel"; // String[] szFileList = Directory.GetFiles(szAppPathName); // if (szFileList.Length > 0) // { // Random r = new Random(TerrainGen.Chaos_GetRandomSeed()); // int nRandomPos = r.Next(szFileList.Length); // String szModelOutputFilename = szFileList[nRandomPos]; // m_listModels.Add(szModelOutputFilename); // } //} m_pModel.copyFromModel(pManualSetPara.m_pModel); //获得当前文件路径下的石头模型文件,并随机获得石块模型 String szAppPathName = ClsGlobal.GetParentPathofExe() + @"Resource\RockModel"; String[] szFileList = Directory.GetFiles(szAppPathName); if (szFileList.Length > 0) { Random r = new Random(TerrainGen.Chaos_GetRandomSeed()); int nRandomPos = r.Next(szFileList.Length); String szModelOutputFilename = szFileList[nRandomPos]; m_listModels.Add(szModelOutputFilename); } //保存当前添加的模型参数 Model pTmpModel = new Model(); pTmpModel.copyFromModel(pManualSetPara.m_pModel); m_manualAddModels.Add(pTmpModel); } else { return; } IZAware za = mapPoint as IZAware; za.ZAware = true; double zVal; IRaster2 pRaster2 = pRasterLayer.Raster as IRaster2; int col, row; pRaster2.MapToPixel(mapPoint.X, mapPoint.Y, out col, out row); zVal = Convert.ToDouble(pRaster2.GetPixelValue(0, col, row)); if (double.IsNaN(zVal)) { MessageBox.Show("获取模型的高度失败!"); return; } if (m_listModels.Count == 0) { MessageBox.Show("请先生成模型!"); return; } mapPoint.Z = zVal; try { //IMultiPatch pMP = new MultiPatchClass(); IFeatureClass pFC = pFeatureLayer.FeatureClass; IFeature pF = pFC.CreateFeature(); IImport3DFile pI3D = new Import3DFileClass(); pI3D.CreateFromFile(m_listModels[m_listModels.Count - 1]); IMultiPatch pMP = pI3D.Geometry as IMultiPatch; ITransform3D pT3D = pMP as ITransform3D; pT3D.Move3D(mapPoint.X, mapPoint.Y, mapPoint.Z); IRasterProps pRasterProps = pRasterLayer.Raster as IRasterProps; double xmax = pRasterProps.Extent.XMax; double xmin = pRasterProps.Extent.XMin; double ymax = pRasterProps.Extent.YMax; double ymin = pRasterProps.Extent.YMin; //生成地形的地理范围 double dbGeoRangeX = xmax - xmin; double dbGeoRangeY = ymax - ymin; double dbModelRangeX = pMP.Envelope.Width; double dbModelRangeY = pMP.Envelope.Height; double dbModelRangeZ = pMP.Envelope.ZMax - pMP.Envelope.ZMin; //根据地形大小改变石块大小 //double dbRandomSize = Math.Min(dbGeoRangeX, dbGeoRangeY) * (0.03 ); //[0.03 0.06] //double dbScale = dbRandomSize / Math.Max(dbModelRangeX, dbModelRangeY); double dbScale = m_pModel.dbSize / Math.Max(dbModelRangeX, Math.Max(dbModelRangeY, dbModelRangeZ)); pT3D.Scale3D(mapPoint, dbScale, dbScale, dbScale); pF.Shape = pMP as IGeometry; pF.Store(); if (pMapCtr != null) { pMapCtr.ActiveView.PartialRefresh(esriViewDrawPhase.esriViewGeography, null, null); } } catch (SystemException e) { MessageBox.Show(e.Message); } } } }
// //获取地图状态信息 // private void GetStatusXY(double mapX, double mapY) { try { if (this._barItemXY != null) { ISpatialReference spatialReference = this._mapControl.SpatialReference; if (spatialReference != null) { if (spatialReference is IProjectedCoordinateSystem) { IProjectedCoordinateSystem projectedCoordinateSystem = spatialReference as IProjectedCoordinateSystem; IPoint point = new PointClass(); point.SpatialReference = spatialReference; point.X = mapX; point.Y = mapY; point.Project(projectedCoordinateSystem.GeographicCoordinateSystem); double lon = point.X; double lat = point.Y; int lon_degree = (int)Math.Floor(Convert.ToDecimal(lon)); int lat_degree = (int)Math.Floor(Convert.ToDecimal(lat)); lon = (lon - lon_degree) * 60; lat = (lat - lat_degree) * 60; int lon_m = (int)Math.Floor(Convert.ToDecimal(lon)); int lat_m = (int)Math.Floor(Convert.ToDecimal(lat)); lon = (lon - lon_m) * 60; lat = (lat - lat_m) * 60; int lon_s = (int)Math.Floor(Convert.ToDecimal(lon)); int lat_s = (int)Math.Floor(Convert.ToDecimal(lat)); string strLon = ""; string strLat = ""; if (lon_degree > 0) { strLon = lon_degree + "° " + lon_m + "′ " + lon_s + "″ E"; } else { strLon = lon_degree + "° " + lon_m + "′ " + lon_s + "″ E"; } if (lat_degree > 0) { strLat = lat_degree + "° " + lat_m + "′ " + lat_s + "″ N"; } else { strLat = lat_degree + "° " + lat_m + "′ " + lat_s + "″ N"; } this._barItemXY.Caption = string.Format("坐标:{0},{1}", strLon, strLat); } } else { this._barItemXY.Caption = string.Format("坐标:{0},{1}", mapX, mapY); } } if (this._barItemRaster != null) { this._barItemRaster.Visibility = BarItemVisibility.Never; if (this._rasterLayer != null) { IRaster2 raster = this._rasterLayer.Raster as IRaster2; IPoint point = new PointClass(); point.X = mapX; point.Y = mapY; point.SpatialReference = this._spatialReference; ISpatialReference spatialReference = (raster as IGeoDataset).SpatialReference; if (!EngineAPI.IsEqualSpatialReference(this._spatialReference, spatialReference)) { point.Project(spatialReference); } int colum; int row; raster.MapToPixel(point.X, point.Y, out colum, out row); if (colum >= 0 && colum <= this._rasterLayer.ColumnCount && row >= 0 && row <= this._rasterLayer.RowCount) { this._barItemRaster.Visibility = BarItemVisibility.Always; double value = CommonAPI.ConvertToDouble(raster.GetPixelValue(0, colum, row)); this._barItemRaster.Caption = string.Format("行:{0}, 列:{1}, 像素值:{2}", row, colum, value); } } } } catch (Exception ex) { Log.WriteLog(typeof(GFSApplication), ex); } }
public static object FindValue(IRaster2 raster, int band, IPoint point) { int col, row; raster.MapToPixel(point.X, point.Y, out col, out row); return raster.GetPixelValue(band, col, row); }