[转]在AutoCAD中根据MapInfo导出DXF文件块属性填充图斑

现状地类
有林地,159255127有林地
农村居民点,255204204农村居民点
望天田,255255110望天田
机耕道,255180178机耕道
旱地,255255183旱地
果园,255223127果园
河流水面,171255255河流水面
荒草地,210255180荒草地
坑塘水面,171255255坑塘水面
裸岩石砾地,192192192裸岩石砾地
祼岩地,255255255祼岩地
农村宅基地,255204204农村宅基地
特殊用地,255132132特殊用地
沟渠,171255255沟渠
工矿用地,255180178工矿用地

 
第一行:"现状地类" 为Mapinfo中的字段名
 
以下行为具体配置,如第一行    有林地,159255127有林地 

第一个"有林地"为字段里的值,后跟的9位数据为RGB颜色,后面的"有林地"是图层名,图层不存在会自动创建
配置文件名为:  d:\xdxah.ini  在程序中此路径和名称固定
 

/* 根据MAPINFO导出块属性和配置文件填充图斑
 * 此程序需一配置文件
 * 作者:王晓东
 * QQ:10516321 Email:xiaook@gmail.com
 * http://goat.cublog.cn
 */

using System.Collections.Generic;
using System.IO;
using System.Text;
using Autodesk.AutoCAD.ApplicationServices;
using Autodesk.AutoCAD.DatabaseServices;
using Autodesk.AutoCAD.EditorInput;
using Autodesk.AutoCAD.Runtime;

/*Copyright © 王晓东 2010

AutoCAD version:AutoCAD 2006
Description: 

To use HatchByBlockAttribute.dll:

1. Start AutoCAD and open a new drawing.
2. Type netload and select HatchByBlockAttribute.dll.
3. Execute the xah command.*/



namespace HatchByBlockAttribute
{
    /// <summary>

    /// Summary for Class1.

    /// </summary>

    public class Class1
    {
        Document acDoc = Application.DocumentManager.MdiActiveDocument;
        Editor acDocEd = Application.DocumentManager.MdiActiveDocument.Editor;
        Database acCurDb =Application.DocumentManager.MdiActiveDocument.Database;
        [CommandMethod("xah")]
        public void xah()
        {
            acDocEd.WriteMessage(@"\n 根据MAPINFO导出块属性和配置文件填充图斑 \n此程序需一配置文件 \n作者:王晓东 \nQQ:10516321 Email:xiaook@gmail.com");
            //读取配置文件

            StreamReader configfs = new StreamReader(@"d:\xdxah.ini",Encoding.Default);
            Dictionary<string, string> confDict = new Dictionary<string,string>();
            string str = configfs.ReadLine(); //提取首行字段名

            string keyField = str;
            str = configfs.ReadLine();

            while (str != null)
            {
                string[] strarr = str.Split(',');
                confDict.Add(strarr[0], strarr[1]);
                str = configfs.ReadLine();
            }
            //选择所有块对象

            ObjectIdCollection acObjIdColl = new ObjectIdCollection();
            PromptSelectionResult acPtRes = acDocEd.SelectAll();

            if (acPtRes.Status == PromptStatus.OK)
            {
                SelectionSet ss = acPtRes.Value;
                acObjIdColl = new ObjectIdCollection(ss.GetObjectIds());
            }

            //事务

            using (Transaction acTrans =acCurDb.TransactionManager.StartTransaction())
            {
                ObjectIdCollection objIdCol = new ObjectIdCollection();
                BlockTable acBlkTbl = acTrans.GetObject(acCurDb.BlockTableId,OpenMode.ForRead) as BlockTable;
                BlockTableRecord acBlkTblRec =acTrans.GetObject(acBlkTbl[BlockTableRecord.ModelSpace], OpenMode.ForWrite) asBlockTableRecord;
                LayerTable acLyrTbl;
                acLyrTbl = acTrans.GetObject(acCurDb.LayerTableId,OpenMode.ForRead) as LayerTable;

                //仅提取所有块参照

                ObjectIdCollection objColTmp = new ObjectIdCollection();
                for (int i = 0; i < acObjIdColl.Count; i++)
                {
                    DBObject dbObject = acTrans.GetObject(acObjIdColl[i],OpenMode.ForRead);
                    if (dbObject is BlockReference)
                    {
                        objColTmp.Add(acObjIdColl[i]);
                    }
                }

                acObjIdColl = objColTmp;
                for (int j = 0; j < acObjIdColl.Count; j++) //遍历对象

                {
                    BlockReference bkRef =(BlockReference)acTrans.GetObject(acObjIdColl[j], OpenMode.ForRead);
                    AttributeCollection attCol = bkRef.AttributeCollection;
                    string sHatchColor = "";
                    Hatch acHatch = new Hatch();
                    acHatch.SetDatabaseDefaults();

                    for (int k = 0; k < attCol.Count; k++) //遍历属性

                    {
                        AttributeReference attRef =(AttributeReference)acTrans.GetObject(attCol[k], OpenMode.ForRead, false, true);
                        if (attRef.Tag == keyField)
                        {
                            for (int i = 0; i < confDict.Count; i++) //编历配置文件项

                            {
                                if (confDict.ContainsKey(attRef.TextString)) //确定字典内是否包含此地类主键

                                {
                                    sHatchColor = confDict[attRef.TextString];

                                }
                            }
                        }
                    }

                    //包含此地类主键,填充此块

                    DBObjectCollection bkDBCol = new DBObjectCollection();
                    bkRef.Explode(bkDBCol);

                    //填充前将此块分解并提取Polyline对象

                    for (int kk = 0; kk < bkDBCol.Count; kk++)
                    {
                        if (bkDBCol[kk] is Polyline)
                        {
                            Polyline pl = (Polyline)bkDBCol[kk];
                            if (pl.Closed) //只填充闭合多线段

                            {
                                ObjectIdCollection bkIDCol = newObjectIdCollection(); //要填充对象的Collection


                                acBlkTblRec.AppendEntity((Entity)bkDBCol[kk]);
                                acTrans.AddNewlyCreatedDBObject(bkDBCol[kk],true);
                                bkIDCol.Add(bkDBCol[kk].ObjectId);
                                acHatch.AppendLoop((int)HatchLoopTypes.Outermost,bkIDCol);
                            }
                        }
                    }

                    //填充



                    if (sHatchColor != "")
                    {

                        byte R = byte.Parse(sHatchColor.Substring(0, 3));
                        byte G = byte.Parse(sHatchColor.Substring(3, 3));
                        byte B = byte.Parse(sHatchColor.Substring(6, 3));
                        string layer = sHatchColor.Substring(9);
                        if (acLyrTbl.Has(layer) == false)
                        {
                            LayerTableRecord acLyrTblRec = newLayerTableRecord();

                            // Assign the layer the ACI color 1 and a name

                            acLyrTblRec.Color =Autodesk.AutoCAD.Colors.Color.FromRgb(R, G, B);
                            acLyrTblRec.Name = layer;

                            // Upgrade the Layer table for write

                            acLyrTbl.UpgradeOpen();

                            // Append the new layer to the Layer table and the transaction

                            acLyrTbl.Add(acLyrTblRec);
                            acTrans.AddNewlyCreatedDBObject(acLyrTblRec, true);
                        }
                        acHatch.Layer = layer;

                        acBlkTblRec.AppendEntity(acHatch);
                        acTrans.AddNewlyCreatedDBObject(acHatch, true);

                        acHatch.SetHatchPattern(HatchPatternType.PreDefined,"SOLID");
                        //acHatch.ColorIndex = int.Parse(sHatchColor);

                        acHatch.Color = Autodesk.AutoCAD.Colors.Color.FromRgb(R,G, B);
                        acHatch.Associative = false;
                        acHatch.EvaluateHatch(true);
                    }

                }

                ////提示清理边界

                //PromptKeywordOptions pKeyOpts = new PromptKeywordOptions("");

                //pKeyOpts.Message = "\n清理对象仅留图案填充[No/Yes]";

                //pKeyOpts.Keywords.Add("Y");

                //pKeyOpts.Keywords.Add("N");

                //pKeyOpts.Keywords.Default = "N";

                //pKeyOpts.AllowNone = true;


                //PromptResult pKeyRes = acDoc.Editor.GetKeywords(pKeyOpts);

                //if (pKeyRes.StringResult == "Y")

                //{

                // //选择所有块对象

                // TypedValue[] tv = new TypedValue[1];

                // //tv.SetValue(new TypedValue((int)DxfCode.Operator, "<not"), 0);

                // tv.SetValue(new TypedValue((int)DxfCode.Start, "HATCH"), 0);

                // //tv.SetValue(new TypedValue((int)DxfCode.Operator, ">not"), 2);

                // SelectionFilter sf = new SelectionFilter(tv);

                // ObjectIdCollection acHatchColl = new ObjectIdCollection();

                // PromptSelectionResult acPtRes1 = acDocEd.SelectAll(sf);

                // ObjectIdCollection acObjForDelColl = new ObjectIdCollection();

                // PromptSelectionResult acPtRes2 = acDocEd.SelectAll();

                // if ((acPtRes1.Status == PromptStatus.OK) && (acPtRes2.Status == PromptStatus.OK))

                // {

                // SelectionSet ss = acPtRes1.Value;

                // acHatchColl = new ObjectIdCollection(ss.GetObjectIds());

                // foreach (ObjectId a in acHatchColl)

                // {

                // acObjForDelColl.Remove(a);

                // }


                // for (int i = 0; i < acObjForDelColl.Count; i++)

                // {

                // DBObject dbobj = acObjForDelColl[i].GetObject(OpenMode.ForRead);

                // dbobj.Erase();

                // }

                // }

                //}

                acTrans.Commit();
            }
        }
    }
}

原文地址:https://www.cnblogs.com/chinaHunk/p/2700868.html