// 创建带文字的线型 ////// 返回线型ID public static ObjectId CreateLineTypeWithText(string lineTypeName, string text) { Document doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument; Database db = doc.Database; Editor ed = doc.Editor; Transaction tr = db.TransactionManager.StartTransaction(); using (tr) { // 读出文字样式表 TextStyleTable tt = (TextStyleTable)tr.GetObject(db.TextStyleTableId, OpenMode.ForRead); // 读出线型表 LinetypeTable lt = (LinetypeTable)tr.GetObject(db.LinetypeTableId, OpenMode.ForWrite); if (lt.Has(lineTypeName)) { return(lt[lineTypeName]); } else // 创建新的线型记录. { LinetypeTableRecord ltr = new LinetypeTableRecord(); // ...设置线型记录特性 ltr.Name = lineTypeName; ltr.AsciiDescription = lineTypeName + " Supply ---- " + text + " ---- " + text + " ---- " + text + " ----"; ltr.PatternLength = 1.1; ltr.NumDashes = 3; //分为三段 // 线段Dash #1 ltr.SetDashLengthAt(0, 0.5); // 线段Dash #2 ltr.SetDashLengthAt(1, -0.3); ltr.SetShapeStyleAt(1, tt["Standard"]); //文字样式设定 ltr.SetShapeNumberAt(1, 0); //文字位置设定,用一二维向量控制 ltr.SetShapeOffsetAt(1, new Vector2d(-0.1, -0.05)); ltr.SetShapeScaleAt(1, 0.1); //文字比例 ltr.SetShapeIsUcsOrientedAt(1, false); ltr.SetShapeRotationAt(1, 0); //文字方向,0为顺直接方向 ltr.SetTextAt(1, text); //文字内容 // 线段Dash #3 ltr.SetDashLengthAt(2, -0.3); // 添加新的线型记录到线型表 ObjectId ltId = lt.Add(ltr); tr.AddNewlyCreatedDBObject(ltr, true); tr.Commit(); return(ltId);//返回线型记录ID } } }
string.Format("Standartization\\{0}\\DataLayers.xml", codeGroup)); // @"Z:\AutoCAD_server\ShareSettings\Standartization" + "\\" + codeGroup + "\\" + "DataLayers.xml"; public List <LayerTableRecord> GetListLayers(Database db, bool isStandart) //Список всех слоев в документе { List <LayerTableRecord> listLayers = new List <LayerTableRecord>(); using (Transaction tr = db.TransactionManager.StartTransaction()) { if (isStandart) { MainForm.dicLineTypes = new Dictionary <long, string>(); LinetypeTable acLinTbl = tr.GetObject(db.LinetypeTableId, OpenMode.ForWrite) as LinetypeTable; foreach (var item in acLinTbl) { LinetypeTableRecord btr = (LinetypeTableRecord)tr.GetObject(item, OpenMode.ForRead); MainForm.dicLineTypes.Add(btr.Id.OldId, btr.Name); } } var layerTable = tr.GetObject(db.LayerTableId, OpenMode.ForWrite) as LayerTable; foreach (var layer in layerTable) { LayerTableRecord ltr = (LayerTableRecord)tr.GetObject(layer, OpenMode.ForWrite, true); ltr.IsLocked = false; listLayers.Add(ltr); } tr.Commit(); } return(listLayers); }
/// <summary> /// Последовательность штрихов и пробелов типа линии /// </summary> /// <param name="ltype"></param> /// <param name="ltScale"></param> /// <returns></returns> public static List <double> GetLinePattern(LinetypeTableRecord ltype, double ltScale = 1) { List <double> pattern = new List <double>(); for (int i = 0; i < ltype.NumDashes; i++) { //Учтена возможность вставки подряд двух пробелов или двух штрихов double dash = ltype.DashLengthAt(i); if (dash != 0) { double dashValue = dash * ltScale; if (i != 0 && Math.Sign(pattern[i - 1]) == Math.Sign(dashValue)) { pattern[i - 1] += dashValue;//такой же знак как и у предыдущего => объединить в один } else { pattern.Add(dashValue);//новый штрих } } } if (pattern.Count == 0)//если данные не получены, то выдать патерн для сплошной линии { pattern.Add(1); } return(pattern); }
public void CheckLinetype() { Document doc = Application.DocumentManager.MdiActiveDocument; Database db = doc.Database; using (Transaction tr = db.TransactionManager.StartTransaction()) { LinetypeTable ltt = tr.GetObject(db.LinetypeTableId, OpenMode.ForRead) as LinetypeTable; //foreach(ObjectId id in ltt) //{ // LinetypeTableRecord lttr = (LinetypeTableRecord)tr.GetObject(id, OpenMode.ForRead); //} if (!ltt.Has("SWALL")) { LinetypeTableRecord lttr = new LinetypeTableRecord(); lttr.Name = "SWALL"; lttr.PatternLength = 0.75; lttr.NumDashes = 3; lttr.Comments = "___________//_______"; lttr.AsciiDescription = "___________//_______"; ltt.UpgradeOpen(); ltt.Add(lttr); tr.AddNewlyCreatedDBObject(lttr, true); tr.Commit(); } } }
public void testLayerIterator() { Database db = HostApplicationServices.WorkingDatabase; Editor ed = Application.DocumentManager.MdiActiveDocument.Editor; StreamWriter textFile = new StreamWriter("c:\\3.txt", false); using (Transaction trans = db.TransactionManager.StartTransaction()) { LayerTable lt = (LayerTable)trans.GetObject(db.LayerTableId, OpenMode.ForRead); LinetypeTable tt = (LinetypeTable)trans.GetObject(db.LinetypeTableId, OpenMode.ForRead); foreach (ObjectId layerId in lt) { LayerTableRecord ltr = (LayerTableRecord)trans.GetObject(layerId, OpenMode.ForRead); String layerName = ltr.Name; String colorName = ltr.Color.ToString(); ObjectId linetypeId = ltr.LinetypeObjectId; LinetypeTableRecord ttr = (LinetypeTableRecord)trans.GetObject(linetypeId, OpenMode.ForRead); String linetypeName = ttr.Name; String withLayer = ltr.LineWeight.ToString(); String str = layerName + " " + colorName + " " + linetypeName + " " + withLayer; textFile.WriteLine(str, false); } textFile.Close(); trans.Commit(); } }
private static LinetypeTableRecord GetLineType(Transaction tr, ObjectId idLineStd, LinetypeTable acLinTbl) { LinetypeTableRecord currentLineType = null; string nameLineType = ""; foreach (var item in MainForm.dicLineTypes) { if (idLineStd.OldId != item.Key) { continue; } nameLineType = item.Value; break; } foreach (var item in acLinTbl) { LinetypeTableRecord lineTbr = (LinetypeTableRecord)tr.GetObject(item, OpenMode.ForRead); if (lineTbr.Name.ToUpper() == nameLineType.ToUpper()) { currentLineType = lineTbr; return(currentLineType); } } return(currentLineType); }
getLinetypeTableRecord(string name) { LinetypeTableRecord LTtr = null; try { using (Transaction tr = BaseObjs.startTransactionDb()) { LinetypeTable LTT = getLineTypeTable(); if (LTT.Has(name) == true) { LTtr = (LinetypeTableRecord)tr.GetObject(LTT[name], OpenMode.ForRead); } else { BaseObjs._db.LoadLineTypeFile(name, "ACAD.LIN"); LTtr = (LinetypeTableRecord)tr.GetObject(LTT[name], OpenMode.ForRead); } tr.Commit(); } } catch (System.Exception ex) { BaseObjs.writeDebug(ex.Message + " LineType.cs: line: 63"); } return(LTtr); }
private static string GetLineTypeName(ObjectId lineTypeId, Database db) { using (Transaction trans = db.TransactionManager.StartTransaction()) { LinetypeTableRecord lineRec = trans.GetObject(lineTypeId, OpenMode.ForRead) as LinetypeTableRecord; if (lineRec != null) { return(lineRec.Name); } } return(null); }
setUpLayers() { ObjectId idLayer = ObjectId.Null; idLayer = Layer.manageLayers("_XX-AUTO DRIVE"); Layer.modifyLayer(idLayer, 63, LineWeight.LineWeight035); idLayer = Layer.manageLayers("_XX-AUTO PARKING"); Layer.modifyLayer(idLayer, 203, LineWeight.LineWeight035); idLayer = Layer.manageLayers("_XX-BUILDING ADJACENT LANDSCAPING"); Layer.modifyLayer(idLayer, 235, LineWeight.LineWeight035); idLayer = Layer.manageLayers("_XX-CONCRETE APRON"); Layer.modifyLayer(idLayer, 180, LineWeight.LineWeight035); idLayer = Layer.manageLayers("_XX-DOCK APRON"); Layer.modifyLayer(idLayer, 6, LineWeight.LineWeight035); idLayer = Layer.manageLayers("_XX-FLOOR SLAB_A"); Layer.modifyLayer(idLayer, 30, LineWeight.LineWeight035); idLayer = Layer.manageLayers("_XX-FLOOR SLAB_B"); Layer.modifyLayer(idLayer, 180, LineWeight.LineWeight035); idLayer = Layer.manageLayers("_XX-FLOOR SLAB_C"); Layer.modifyLayer(idLayer, 14, LineWeight.LineWeight035); idLayer = Layer.manageLayers("_XX-FRONT LANDSCAPING"); Layer.modifyLayer(idLayer, 35, LineWeight.LineWeight035); idLayer = Layer.manageLayers("_XX-OFFICE SLAB AND SAND"); Layer.modifyLayer(idLayer, 153, LineWeight.LineWeight035); idLayer = Layer.manageLayers("_XX-TRUCK PAVING"); Layer.modifyLayer(idLayer, 114, LineWeight.LineWeight035); idLayer = Layer.manageLayers("_YY-K BRACE"); Layer.modifyLayer(idLayer, 45, LineWeight.LineWeight035); idLayer = Layer.manageLayers("GRADING LIMIT"); Layer.modifyLayer(idLayer, 1, LineWeight.LineWeight035); LinetypeTableRecord lttr = LineType.getLinetypeTableRecord("HIDDEN"); using (var tr = BaseObjs.startTransactionDb()){ LayerTableRecord ltr = (LayerTableRecord)tr.GetObject(idLayer, OpenMode.ForWrite); ltr.LinetypeObjectId = lttr.ObjectId; } }
public void TestAddLinetype() { var newId = ObjectId.Null; using (var db = AcadDatabase.Active()) { var newLinetype = new LinetypeTableRecord() { Name = "NewLinetype" }; db.Linetypes.Add(newLinetype); newId = newLinetype.ObjectId; } AcadAssert.That.LinetypeTable.Contains(newId); }
/// <summary> /// 创建一个新的线型 /// </summary> /// <param name="db">数据库对象</param> /// <param name="typeName">线型名</param> /// <returns>返回新建线型的Id</returns> public static ObjectId AddLineType(this Database db, string typeName) { //打开线型表 LinetypeTable lt = (LinetypeTable)db.LinetypeTableId.GetObject(OpenMode.ForRead); if (!lt.Has(typeName)) //如果存在名为typeName的线型表记录 { lt.UpgradeOpen(); //切换线型表为写 //新建一个线型表记录 LinetypeTableRecord ltr = new LinetypeTableRecord(); ltr.Name = typeName; //设置线型表记录的名称 lt.Add(ltr); //将新的线型表记录的信息添加到的线型表中 db.TransactionManager.AddNewlyCreatedDBObject(ltr, true); lt.DowngradeOpen(); //为了安全,将线型表的状态切换为读 } return(lt[typeName]); //返回新添加的线型表记录的ObjectId }
public crawlAcDbLayerTableRecord(LayerTableRecord layerRecord) { Name = layerRecord.Name; LinetypeTableRecord ltRec = (LinetypeTableRecord)layerRecord.LinetypeObjectId.GetObject(OpenMode.ForRead); this.Linetype = ltRec.Name; this.LineWeight = layerRecord.LineWeight.ToString(); this.IsFrozen = layerRecord.IsFrozen; this.IsHidden = layerRecord.IsHidden; this.IsOff = layerRecord.IsOff; this.IsPlottable = layerRecord.IsPlottable; this.Color = layerRecord.Color.ToString(); this.ObjectId = layerRecord.ObjectId.ToString(); }
bool InitLinetype() { using (var tr = acDoc.TransactionManager.StartTransaction()) { var ltt = tr.GetObject(acCurDb.LinetypeTableId, OpenMode.ForRead) as LinetypeTable; try { dashed = tr.GetObject(ltt["DASHED"], OpenMode.ForRead) as LinetypeTableRecord; } catch (Exception) { Tweet("Не удалось загрузить типы линий"); return(false); } } return(true); }
private static void SetLayerProperties(LayerTableRecord stdLayer, LayerTableRecord ltr, Database db, Transaction tr) { ltr.Color = stdLayer.Color; ltr.LineWeight = stdLayer.LineWeight; ObjectIdCollection acObjIdColl = new ObjectIdCollection(); acObjIdColl.Add(stdLayer.LinetypeObjectId); IdMapping acIdMap = new IdMapping(); LinetypeTable acLinTbl; acLinTbl = tr.GetObject(db.LinetypeTableId, OpenMode.ForWrite) as LinetypeTable; db.WblockCloneObjects(acObjIdColl, acLinTbl.Id, acIdMap, DuplicateRecordCloning.Ignore, false); LinetypeTableRecord currentLineType = GetLineType(tr, stdLayer.LinetypeObjectId, acLinTbl); ltr.LinetypeObjectId = currentLineType.Id; ltr.IsPlottable = stdLayer.IsPlottable; ltr.Description = stdLayer.Description; }
public ArrayList GetLineTypes() { ArrayList lineTypes = new ArrayList(); Document doc = Application.DocumentManager.MdiActiveDocument; Database db = doc.Database; using (Transaction trans = db.TransactionManager.StartTransaction()) { LinetypeTable liTab = trans.GetObject(db.LinetypeTableId, OpenMode.ForRead) as LinetypeTable; foreach (var li in liTab) { LinetypeTableRecord litr = trans.GetObject(li, OpenMode.ForRead) as LinetypeTableRecord; lineTypes.Add(litr.Name); } } return(lineTypes); }
/// <summary> /// Найти тип линии - непрерывный (независимо от его названия) /// </summary> /// <param name="db"></param> /// <returns></returns> public static ObjectId GetContinuousLinetype(Database db) { using (Transaction tr = db.TransactionManager.StartTransaction()) { LinetypeTable lt = (LinetypeTable)tr.GetObject(db.LinetypeTableId, OpenMode.ForRead); foreach (ObjectId ltrId in lt) { LinetypeTableRecord ltr = (LinetypeTableRecord)tr.GetObject(ltrId, OpenMode.ForRead); List <double> pattern = GetLinePattern(ltr); if (pattern.Count == 1 && pattern[0] > 0) { return(ltrId); } } tr.Commit(); } return(ObjectId.Null); }
/// <summary> /// Opens an AutoCAD linetype dialog box to let the user choose a linetype for the currently selected layer /// </summary> private void SelectLine() { Document doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument; Database db = doc.Database; Editor ed = doc.Editor; // default setting for linetype, in case one is not selected string lineName = "Continuous"; LinetypeDialog ltd = new LinetypeDialog(); // using will close connection when finished. Causes problems otherwise using (Transaction tr = db.TransactionManager.StartTransaction()) { LinetypeTable lt = (LinetypeTable)tr.GetObject(db.LinetypeTableId, OpenMode.ForRead); DialogResult dr = ltd.ShowDialog(); // if OK is clicked on linetype dialog box if (dr == DialogResult.OK) { LinetypeTableRecord symbol = (LinetypeTableRecord)tr.GetObject(ltd.Linetype, OpenMode.ForRead); // if user does not select ByLayer or ByBlock as linetype, set lineName to their selection // otherwise, leave it as Continuous if (!symbol.Name.Equals("ByLayer") && !symbol.Name.Equals("ByBlock")) { lineName = symbol.Name; } } } // set line in selected Layer in layerList //// layerList[the selected layer name] this.layerList[this.layersListBox.SelectedItem.ToString()].SetLine(lineName); // brings form back to the front this.Activate(); }
/// <summary> /// 窗体加载事件 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void Window_Loaded(object sender, RoutedEventArgs e) { Document doc = AcadApp.DocumentManager.MdiActiveDocument; Editor ed = doc.Editor; Database db = doc.Database; using (Transaction trans = db.TransactionManager.StartTransaction()) { #region 线型 LinetypeTable lt = db.LinetypeTableId.GetObject(OpenMode.ForRead) as LinetypeTable; //获取线型表 foreach (ObjectId ltrId in lt) //遍历线型表记录 { LinetypeTableRecord ltr = ltrId.GetObject(OpenMode.ForRead) as LinetypeTableRecord; if (ltr != null) { this.comboBoxInnerLineStyle.Items.Add(ltr.Name); //将线型名加入内框comboBox this.comboBoxOuterLineStyle.Items.Add(ltr.Name); //将线型名加入外框comboBox } } //设置默认选择为"ByLayer" this.comboBoxInnerLineStyle.SelectedItem = "ByLayer"; this.comboBoxOuterLineStyle.SelectedItem = "ByLayer"; #endregion #region 字体 TextStyleTable tst = db.TextStyleTableId.GetObject(OpenMode.ForRead) as TextStyleTable; //获取文字样式表 foreach (ObjectId tstrId in tst) //遍历文字样式表记录 { TextStyleTableRecord tstr = tstrId.GetObject(OpenMode.ForRead) as TextStyleTableRecord; if (tstr != null) { this.comboBoxTextStyle.Items.Add(tstr.Name); } } //设置默认选择为当前字体 TextStyleTableRecord curTstr = db.Textstyle.GetObject(OpenMode.ForRead) as TextStyleTableRecord; this.comboBoxTextStyle.SelectedItem = curTstr.Name; #endregion trans.Commit(); } }
ObjectId GetProcessLayer(Transaction trans) { ObjectId layerId; string layerName = "Обработка"; LayerTable layerTbl = trans.GetObject(Database.LayerTableId, OpenMode.ForRead) as LayerTable; if (layerTbl.Has(layerName)) // Проверяем нет ли еще слоя с таким именем в чертеже { layerId = layerTbl[layerName]; } else // создание нового слоя { layerTbl.UpgradeOpen(); LayerTableRecord layer = new LayerTableRecord(); layer.Name = layerName; layer.Color = AcCl.Color.FromColor(System.Drawing.Color.Red); LinetypeTable lineTypeTbl = ((LinetypeTable)(trans.GetObject(Database.LinetypeTableId, OpenMode.ForWrite))); ObjectId lineTypeID; string ltypeName = "Continuous"; if (lineTypeTbl.Has(ltypeName)) { lineTypeID = lineTypeTbl[ltypeName]; } else // создания стиля линий { LinetypeTableRecord lineType = new LinetypeTableRecord(); lineType.Name = ltypeName; lineTypeTbl.Add(lineType); trans.AddNewlyCreatedDBObject(lineType, true); lineTypeID = lineType.ObjectId; } layer.LinetypeObjectId = lineTypeID; layer.IsPlottable = true; layerId = layerTbl.Add(layer); trans.AddNewlyCreatedDBObject(layer, true); } return(layerId); }
Stream(ArrayList data, LinetypeTableRecord rec) { data.Add(new Snoop.Data.ClassSeparator(typeof(LinetypeTableRecord))); data.Add(new Snoop.Data.String("Ascii Description", rec.AsciiDescription)); data.Add(new Snoop.Data.String("Comments", rec.Comments)); data.Add(new Snoop.Data.Bool("Is scaled to fit", rec.IsScaledToFit)); data.Add(new Snoop.Data.Distance("Pattern length", rec.PatternLength)); data.Add(new Snoop.Data.Int("Number of dashes", rec.NumDashes)); int i, len; len = rec.NumDashes; for (i = 0; i < len; i++) { data.Add(new Snoop.Data.CategorySeparator(string.Format("--- DASH [{0}] ---", i))); data.Add(new Snoop.Data.Distance("Length", rec.DashLengthAt(i))); data.Add(new Snoop.Data.ObjectId("Shape style", rec.ShapeStyleAt(i))); data.Add(new Snoop.Data.Int("Shape number at", rec.ShapeNumberAt(i))); data.Add(new Snoop.Data.Vector2d("Shape offset at", rec.ShapeOffsetAt(i))); data.Add(new Snoop.Data.Double("Shape scale at", rec.ShapeScaleAt(i))); data.Add(new Snoop.Data.Bool("Shape is UCS oriented at", rec.ShapeIsUcsOrientedAt(i))); data.Add(new Snoop.Data.Angle("Shape rotation at", rec.ShapeRotationAt(i))); try { data.Add(new Snoop.Data.String("Text at", rec.TextAt(i))); } catch (Autodesk.AutoCAD.Runtime.Exception e) { if (e.ErrorStatus == Autodesk.AutoCAD.Runtime.ErrorStatus.NotApplicable) { data.Add(new Snoop.Data.Exception("Text at", e)); } else { throw e; } } } }
public static ObjectId AddLineType(this Database db, string typeName) { LinetypeTable lt = (LinetypeTable)db.LinetypeTableId.GetObject(OpenMode.ForRead); if (!lt.Has(typeName)) { lt.UpgradeOpen(); LinetypeTableRecord ltr = new LinetypeTableRecord { Name = typeName }; lt.Add(ltr); db.TransactionManager.AddNewlyCreatedDBObject(ltr, true); lt.DowngradeOpen(); } return(lt[typeName]); }
private List <string> BuildLinetypeList() { List <string> list = new List <string>(); list.Add(AfaStrings.AnyValue); Document document = AfaDocData.ActiveDocData.Document; Database database = document.Database; try { using (document.LockDocument((DocumentLockMode)20, null, null, false)) { var transactionManager = database.TransactionManager; using (Transaction transaction = transactionManager.StartTransaction()) { LinetypeTable linetypeTable = (LinetypeTable)transaction.TransactionManager.GetObject(database.LinetypeTableId, 0, false); using (SymbolTableEnumerator enumerator = linetypeTable.GetEnumerator()) { while (enumerator.MoveNext()) { ObjectId current = enumerator.Current; LinetypeTableRecord linetypeTableRecord = (LinetypeTableRecord)transaction.TransactionManager.GetObject(current, 0, false); if (!linetypeTableRecord.IsErased) { list.Add(linetypeTableRecord.Name); } } } transaction.Commit(); } } } catch { } list.Add("Select from entity..."); return(list); }
public static ObjectId LineAttribute(TypeofLine lt) { Editor ed = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.Editor; Database db = ed.Document.Database; Transaction trans = db.TransactionManager.StartTransaction(); ObjectId ltId = ObjectId.Null; if (lt == TypeofLine.ImaginaryLine) { LinetypeTable ltt = (LinetypeTable)trans.GetObject(db.LinetypeTableId, OpenMode.ForWrite); if (ltt.Has("ImaginaryLine")) { ltId = ltt["ImaginaryLine"]; } else { //create new line type LinetypeTableRecord ltr = new LinetypeTableRecord(); //line properties ltr.AsciiDescription = "ImaginaryLineForPipe"; ltr.PatternLength = 1.0; ltr.NumDashes = 2; ltr.SetDashLengthAt(0, 0.5); ltr.SetDashLengthAt(1, -0.5); ltr.Name = "ImaginaryLine"; ltId = ltt.Add(ltr); trans.AddNewlyCreatedDBObject(ltr, true); trans.Commit(); trans.Dispose(); } } return(ltId); }
// 创建直线 // <param name="p1"></param> // <param name="p2"></param> // <returns>id of the line object</returns> public static ObjectId createLine(Point3d p1, Point3d p2, TypeofLine lt = TypeofLine.StraghtLine) { ObjectId createdLineId = new ObjectId(); Editor ed = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.Editor; Database db = ed.Document.Database; Transaction trans = db.TransactionManager.StartTransaction(); try { //TODO: create other new line types ObjectId ltId = ObjectId.Null; if (lt == TypeofLine.ImaginaryLine) { LinetypeTable ltt = (LinetypeTable)trans.GetObject(db.LinetypeTableId, OpenMode.ForWrite); if (ltt.Has("ImaginaryLine")) ltId = ltt["ImaginaryLine"]; else { //create new line type LinetypeTableRecord ltr = new LinetypeTableRecord(); //line properties ltr.AsciiDescription = "ImaginaryLineForPipe"; ltr.PatternLength = 1.0; ltr.NumDashes = 2; ltr.SetDashLengthAt(0, 0.5); ltr.SetDashLengthAt(1, -0.5); ltr.Name = "ImaginaryLine"; ltId = ltt.Add(ltr); trans.AddNewlyCreatedDBObject(ltr, true); } } Line l = new Line((Point3d)p1, (Point3d)p2); BlockTableRecord btr = (BlockTableRecord)trans.GetObject(db.CurrentSpaceId, OpenMode.ForWrite); // now the circle to the current space, model space more than likely if (lt == TypeofLine.ImaginaryLine) l.LinetypeId = ltId; createdLineId = btr.AppendEntity(l); // tell the transaction about the new circle so that it can autoclose it trans.AddNewlyCreatedDBObject(l, true); // now commit the transaction trans.Commit(); } catch (System.Exception ex) { ed.WriteMessage("Problem:" + ex.Message); } finally { trans.Dispose(); } return createdLineId; }
public static ObjectId LineAttribute(TypeofLine lt) { Editor ed = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.Editor; Database db = ed.Document.Database; Transaction trans = db.TransactionManager.StartTransaction(); ObjectId ltId = ObjectId.Null; if (lt == TypeofLine.ImaginaryLine) { LinetypeTable ltt = (LinetypeTable)trans.GetObject(db.LinetypeTableId, OpenMode.ForWrite); if (ltt.Has("ImaginaryLine")) ltId = ltt["ImaginaryLine"]; else { //create new line type LinetypeTableRecord ltr = new LinetypeTableRecord(); //line properties ltr.AsciiDescription = "ImaginaryLineForPipe"; ltr.PatternLength = 1.0; ltr.NumDashes = 2; ltr.SetDashLengthAt(0, 0.5); ltr.SetDashLengthAt(1, -0.5); ltr.Name = "ImaginaryLine"; ltId = ltt.Add(ltr); trans.AddNewlyCreatedDBObject(ltr, true); trans.Commit(); trans.Dispose(); } } return ltId; }
static public void BlockSimplfy() { Document doc = Application.DocumentManager.MdiActiveDocument; Database db = doc.Database; Editor ed = doc.Editor; PromptEntityOptions peopt = new PromptEntityOptions("\nSelect block reference"); peopt.SetRejectMessage("\nSelect only block reference"); peopt.AddAllowedClass(typeof(BlockReference), false); peopt.AllowNone = false; PromptEntityResult peres = ed.GetEntity(peopt); if (peres != null) { try { using (Transaction tx = db.TransactionManager.StartTransaction()) { BlockReference bref = tx.GetObject(peres.ObjectId, OpenMode.ForRead) as BlockReference; BlockTableRecord btrec = null; LayerTable laytab = tx.GetObject(db.LayerTableId, OpenMode.ForRead) as LayerTable; LayerTableRecord laytabrec = null; if (bref.IsDynamicBlock) { btrec = tx.GetObject(bref.DynamicBlockTableRecord, OpenMode.ForRead) as BlockTableRecord; } else { btrec = tx.GetObject(bref.BlockTableRecord, OpenMode.ForRead) as BlockTableRecord; } if (btrec != null) { ed.WriteMessage("Block name is : " + btrec.Name + "\n"); } foreach (ObjectId oid in btrec) { Entity en = tx.GetObject(oid, OpenMode.ForWrite) as Entity; //DBObject dbObj = tx.GetObject(oid, OpenMode.ForRead) as DBObject; ed.WriteMessage("\nType : " + en.GetType().Name); if (en is Dimension) { ed.WriteMessage("\nDimension detected..." + en); continue; } else { // Get entity properties int en_clr = en.ColorIndex; string en_lt = en.Linetype; LineWeight en_lw = en.LineWeight; ed.WriteMessage("\nEntity color/linetype/lineweight is : " + en_clr + "/" + en_lt + "/" + en_lw + "/n"); // Get entity's layer properties laytabrec = tx.GetObject(laytab[en.Layer], OpenMode.ForRead) as LayerTableRecord; Color laytabrec_clr = laytabrec.Color; ObjectId laytabrec_lt_oid = laytabrec.LinetypeObjectId; LinetypeTableRecord ltrec = tx.GetObject(laytabrec_lt_oid, OpenMode.ForRead) as LinetypeTableRecord; string laytabrec_lt_name = ltrec.Name; LineWeight laytabrec_lw = laytabrec.LineWeight; ed.WriteMessage("\nEntity layers color/linetype/lineweight is : " + laytabrec_clr + "/" + laytabrec_lt_name + "/" + laytabrec_lw); // Final setting if (en_clr == 256) { en.Color = laytabrec_clr; } if (en_lt == "ByLayer") { en.Linetype = laytabrec_lt_name; } if (en_lw == LineWeight.ByLayer) { en.LineWeight = laytabrec_lw; } en.Layer = "0"; } } ed.Regen(); tx.Commit(); } } catch (Autodesk.AutoCAD.Runtime.Exception ex) { Application.ShowAlertDialog("Exception occured : \n" + ex.Message); } } }
/// <summary> /// Получить стиль элемента обработки для действия /// </summary> /// <param name="trans"></param> /// <param name="processAction">Действие</param> /// <returns></returns> private static ObjectId GetProcessLayer(Transaction trans, ActionType processAction) { ObjectId layerId; string layerName = processAction.ToString(); LayerTable layerTbl = trans.GetObject(Database.LayerTableId, OpenMode.ForRead) as LayerTable; if (layerTbl.Has(layerName)) // Проверяем нет ли еще слоя с таким именем в чертеже { layerId = layerTbl[layerName]; } else // создание нового слоя { layerTbl.UpgradeOpen(); LayerTableRecord layer = new LayerTableRecord(); layer.Name = layerName; switch (processAction) { case ActionType.Move: case ActionType.InitialMove: layer.Color = Color.FromColor(System.Drawing.Color.Crimson); break; case ActionType.Cutting: case ActionType.Penetration: layer.Color = Color.FromColor(System.Drawing.Color.Green); break; case ActionType.Direction: layer.Color = Color.FromColor(System.Drawing.Color.SpringGreen); break; case ActionType.EngageMove: case ActionType.AapproachMove: layer.Color = Color.FromColor(System.Drawing.Color.Blue); break; case ActionType.RetractMove: case ActionType.DepartureMove: layer.Color = Color.FromColor(System.Drawing.Color.White); break; } LinetypeTable lineTypeTbl = ((LinetypeTable)(trans.GetObject(Database.LinetypeTableId, OpenMode.ForWrite))); ObjectId lineTypeID; string ltypeName = "Continuous"; if (lineTypeTbl.Has(ltypeName)) { lineTypeID = lineTypeTbl[ltypeName]; } else // создания стиля линий { LinetypeTableRecord lineType = new LinetypeTableRecord(); lineType.Name = ltypeName; lineTypeTbl.Add(lineType); trans.AddNewlyCreatedDBObject(lineType, true); lineTypeID = lineType.ObjectId; } layer.LinetypeObjectId = lineTypeID; layer.IsPlottable = true; layerId = layerTbl.Add(layer); trans.AddNewlyCreatedDBObject(layer, true); } return(layerId); }
// 创建直线 // <param name="p1"></param> // <param name="p2"></param> // <returns>id of the line object</returns> public static ObjectId createLine(Point3d p1, Point3d p2, TypeofLine lt = TypeofLine.StraghtLine) { ObjectId createdLineId = new ObjectId(); Editor ed = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.Editor; Database db = ed.Document.Database; Transaction trans = db.TransactionManager.StartTransaction(); try { //TODO: create other new line types ObjectId ltId = ObjectId.Null; if (lt == TypeofLine.ImaginaryLine) { LinetypeTable ltt = (LinetypeTable)trans.GetObject(db.LinetypeTableId, OpenMode.ForWrite); if (ltt.Has("ImaginaryLine")) { ltId = ltt["ImaginaryLine"]; } else { //create new line type LinetypeTableRecord ltr = new LinetypeTableRecord(); //line properties ltr.AsciiDescription = "ImaginaryLineForPipe"; ltr.PatternLength = 1.0; ltr.NumDashes = 2; ltr.SetDashLengthAt(0, 0.5); ltr.SetDashLengthAt(1, -0.5); ltr.Name = "ImaginaryLine"; ltId = ltt.Add(ltr); trans.AddNewlyCreatedDBObject(ltr, true); } } Line l = new Line((Point3d)p1, (Point3d)p2); BlockTableRecord btr = (BlockTableRecord)trans.GetObject(db.CurrentSpaceId, OpenMode.ForWrite); // now the circle to the current space, model space more than likely if (lt == TypeofLine.ImaginaryLine) { l.LinetypeId = ltId; } createdLineId = btr.AppendEntity(l); // tell the transaction about the new circle so that it can autoclose it trans.AddNewlyCreatedDBObject(l, true); // now commit the transaction trans.Commit(); } catch (System.Exception ex) { ed.WriteMessage("Problem:" + ex.Message); } finally { trans.Dispose(); } return(createdLineId); }
Stream(ArrayList data, AcDb.SymbolTableRecord tblRec) { data.Add(new Snoop.Data.ClassSeparator(typeof(AcDb.SymbolTableRecord))); data.Add(new Snoop.Data.String("Name", tblRec.Name)); data.Add(new Snoop.Data.Bool("Is dependent", tblRec.IsDependent)); data.Add(new Snoop.Data.Bool("Is resolved", tblRec.IsResolved)); // branch to all known major sub-classes AbstractViewTableRecord viewRec = tblRec as AbstractViewTableRecord; if (viewRec != null) { Stream(data, viewRec); return; } BlockTableRecord blkRec = tblRec as BlockTableRecord; if (blkRec != null) { Stream(data, blkRec); return; } DimStyleTableRecord dimRec = tblRec as DimStyleTableRecord; if (dimRec != null) { Stream(data, dimRec); return; } LayerTableRecord layRec = tblRec as LayerTableRecord; if (layRec != null) { Stream(data, layRec); return; } LinetypeTableRecord ltypeRec = tblRec as LinetypeTableRecord; if (ltypeRec != null) { Stream(data, ltypeRec); return; } TextStyleTableRecord textRec = tblRec as TextStyleTableRecord; if (textRec != null) { Stream(data, textRec); return; } UcsTableRecord ucsRec = tblRec as UcsTableRecord; if (ucsRec != null) { Stream(data, ucsRec); return; } }
private ObjectId ProcessEntity(Polyline curve, BlockTable bt) { Database db = bt.Database; ObjectId createdBtrId = ObjectId.Null; using (Transaction tr = db.TransactionManager.StartTransaction()) { //Масштаб типа линии double ltScale = curve.LinetypeScale; //Глобальная ширина линии double offsetDist = 0; offsetDist = (curve as Polyline).GetStartWidthAt(0) / 2; if (offsetDist == 0) { throw new System.Exception("Не определена глобальная ширина кривой"); } //Анализ типа линии. Получить длину штриха и длину пробела LinetypeTableRecord ltype = tr.GetObject(curve.LinetypeId, OpenMode.ForRead) as LinetypeTableRecord; //Создать слой, который будет называться как тип линии string layerName = curve.Linetype; LayerTableRecord layerSample = tr.GetObject(curve.LayerId, OpenMode.ForRead) as LayerTableRecord; ObjectId layerId = Utils.CreateLayerIfNotExists(layerName, db, tr, layerSample); //string ltypeDef = ltype.Comments; //double patternLength = ltype.PatternLength; //int numDashes = ltype.NumDashes; if (ltype.Name.Equals("ByLayer")) { ltype = tr.GetObject(layerSample.LinetypeObjectId, OpenMode.ForRead) as LinetypeTableRecord; } List <double> pattern = Utils.GetLinePattern(ltype, ltScale); bool startFromDash = false;//паттерн начинается со штриха (не пробела) if (pattern.Count > 0) { startFromDash = pattern[0] > 0; } DoubleCollection splittingParams = new DoubleCollection(); if (pattern.Count > 1) { //Расчитать параметры для разбивки полилинии double currParam = curve.StartParam; double currDist = curve.GetDistanceAtParameter(currParam); double length = curve.GetDistanceAtParameter(curve.EndParam); int dashNum = 0; while (true) { currDist += Math.Abs(pattern[dashNum]); if (currDist < length) { currParam = curve.GetParameterAtDistance(currDist); //Параметр в конце текущего штриха int nextDashNum = (dashNum + 1) % pattern.Count; //следующий штрих согласно паттерну if (Math.Sign(pattern[dashNum]) != Math.Sign(pattern[nextDashNum])) { //Если знаки текущего штриха и следующего разные //(то есть граница между штрихом и пробелом), //то добавить текущий параметр в разделители splittingParams.Add(currParam); } dashNum = nextDashNum;//переход к следующему штриху } else { break; } } } List <Curve> curves = new List <Curve>(); if (splittingParams.Count != 0) { //Использовать метод Curve.GetSplitCurves для создания сегментов DBObjectCollection splitted = curve.GetSplitCurves(splittingParams); foreach (DBObject dbo in splitted) { if (dbo is Curve) { curves.Add(dbo as Curve); } } } else//Сплошная линия { object o = curve.Clone(); if (o != null && o is Curve) { curves.Add(o as Curve); } } if (curves.Count > 0) { //Создать новый блок для сохранения замкнутых контуров BlockTableRecord btr = new BlockTableRecord(); btr.Name = Guid.NewGuid().ToString(); n++; createdBtrId = bt.Add(btr); tr.AddNewlyCreatedDBObject(btr, true); if (createdBtrId != ObjectId.Null) { bool currIsDash = startFromDash; foreach (Curve axisCurve in curves) { if (currIsDash) { //Использовать метод Curve.GetOffsetCurves //для создания линий границ справа и слева в соответствии с глобальной шириной //Создание замкнутого контура в новом блоке DBObjectCollection offsetCurves = axisCurve.GetOffsetCurves(offsetDist); Curve c1 = Utils.GetFirstDBObject(offsetCurves) as Curve; offsetCurves = axisCurve.GetOffsetCurves(-offsetDist); Curve c2 = Utils.GetFirstDBObject(offsetCurves) as Curve; if (!curve.Closed)//Если кривая не замкнута, то попытаться построить замкнутый контур из правой и левой кривой отступа { try { Line concatLine = new Line(c1.EndPoint, c2.EndPoint /*.StartPoint*/); IntegerCollection joined = c1.JoinEntities(new Entity[] { concatLine, c2 }); if (joined.Count < 2) { throw new System.Exception("Соединение примитивов не выполнено"); } if (c1 is Polyline) { PrepareCurve(c1, layerId); } else { throw new System.Exception("При соединении примитивов создан невалидный объект"); } btr.AppendEntity(c1); tr.AddNewlyCreatedDBObject(c1, true); } catch (System.Exception ex) { ed.WriteMessage("\nВНИМАНИЕ: Возникла ошибка при попытке создания контура в блоке " + btr.Name); } } else//Если кривая замкнута, то просто создать левую и правую кривую { PrepareCurve(c1, layerId); PrepareCurve(c2, layerId); btr.AppendEntity(c1); tr.AddNewlyCreatedDBObject(c1, true); btr.AppendEntity(c2); tr.AddNewlyCreatedDBObject(c2, true); } } currIsDash = !currIsDash;//Считаем, что штрихи и пробелы встречаются строго поочереди } } } tr.Commit(); } return(createdBtrId); }
public static void AddDimStyle(DimStyle dimStyle) { Document document = Active.Document; Database database = document.Database; try { DimStyleTable dimStyleTable = GetDimStyleTable(); TextStyleTableRecord textStyleTableRecord = GetTextStyle(dimStyle.TextStyle); using (Transaction transaction = database.TransactionManager.StartTransaction()) { LinetypeTableRecord lineTypeTableRecord = GetLineType(transaction, "ByLayer"); if (textStyleTableRecord != null & lineTypeTableRecord != null) { DimStyleTableRecord dimStyleTableRecord = new DimStyleTableRecord(); dimStyleTableRecord.Name = dimStyle.Name; // Lines & Arrows dimStyleTableRecord.Dimasz = dimStyle.TextHeight; dimStyleTableRecord.Dimlwd = LineWeight.ByLayer; dimStyleTableRecord.Dimlwe = LineWeight.ByLayer; dimStyleTableRecord.Dimsd1 = false; dimStyleTableRecord.Dimsd2 = false; dimStyleTableRecord.Dimclrd = Color.FromColorIndex(ColorMethod.ByAci, Constants.COLOR_INDEX_BYLAYER); dimStyleTableRecord.Dimltype = lineTypeTableRecord.ObjectId; dimStyleTableRecord.Dimdle = 0; dimStyleTableRecord.Dimltex1 = lineTypeTableRecord.ObjectId; dimStyleTableRecord.Dimltex2 = lineTypeTableRecord.ObjectId; dimStyleTableRecord.Dimse1 = false; dimStyleTableRecord.Dimse2 = false; dimStyleTableRecord.DimfxlenOn = false; dimStyleTableRecord.Dimfxlen = 1; dimStyleTableRecord.Dimclre = Color.FromColorIndex(ColorMethod.ByAci, Constants.COLOR_INDEX_BYLAYER); dimStyleTableRecord.Dimexe = 0.18; dimStyleTableRecord.Dimexo = 0; // Text dimStyleTableRecord.Dimtfill = 0; dimStyleTableRecord.Dimfrac = 0; dimStyleTableRecord.Dimclrt = Color.FromColorIndex(ColorMethod.ByAci, Constants.COLOR_INDEX_BYLAYER); dimStyleTableRecord.Dimtxt = dimStyle.TextHeight; dimStyleTableRecord.Dimgap = 0.5; dimStyleTableRecord.Dimtih = false; dimStyleTableRecord.Dimtoh = false; dimStyleTableRecord.Dimjust = 0; dimStyleTableRecord.Dimtad = 1; dimStyleTableRecord.Dimtxsty = textStyleTableRecord.ObjectId; // Fit dimStyleTableRecord.Dimtofl = true; dimStyleTableRecord.Dimsoxd = false; dimStyleTableRecord.Dimtix = false; dimStyleTableRecord.Dimscale = dimStyle.DimScale; dimStyleTableRecord.Dimatfit = 3; dimStyleTableRecord.Dimtmove = 0; // Primary Units dimStyleTableRecord.Dimdsep = Char.Parse("."); dimStyleTableRecord.Dimpost = ""; dimStyleTableRecord.Dimrnd = 0; dimStyleTableRecord.Dimlfac = 1; dimStyleTableRecord.Dimlunit = 2; dimStyleTableRecord.Dimazin = 2; dimStyleTableRecord.Dimzin = 8; dimStyleTableRecord.Dimdec = 1; // Alternate Units dimStyleTableRecord.Dimalt = false; // Tolerances dimStyleTableRecord.Dimtol = false; dimStyleTable.Add(dimStyleTableRecord); transaction.AddNewlyCreatedDBObject(dimStyleTableRecord, true); }//if transaction.Commit(); }//using } catch (Exception ex) { Active.WriteMessage(ex.Message); throw; } }