/// <summary> /// 在AutoCAD图形中插入块参照 /// </summary> /// <param name="spaceId">块参照要加入的模型空间或图纸空间的Id</param> /// <param name="layer">块参照要加入的图层名</param> /// <param name="blockName">块参照所属的块名</param> /// <param name="position">插入点</param> /// <param name="scale">缩放比例</param> /// <param name="rotateAngle">旋转角度</param> /// <returns>返回块参照的Id</returns> public static ObjectId InsertBlockReference(this ObjectId spaceId, string layer, string blockName, Point3d position, Scale3d scale, double rotateAngle) { ObjectId blockRefId; //存储要插入的块参照的Id Database db = spaceId.Database; //获取数据库对象 //以读的方式打开块表 BlockTable bt = (BlockTable)db.BlockTableId.GetObject(OpenMode.ForRead); //如果没有blockName表示的块,则程序返回 if (!bt.Has(blockName)) { return(ObjectId.Null); } //以写的方式打开空间(模型空间或图纸空间) BlockTableRecord space = (BlockTableRecord)spaceId.GetObject(OpenMode.ForWrite); //创建一个块参照并设置插入点 BlockReference br = new BlockReference(position, bt[blockName]); br.ScaleFactors = scale; //设置块参照的缩放比例 br.Layer = layer; //设置块参照的层名 br.Rotation = rotateAngle; //设置块参照的旋转角度 ObjectId btrId = bt[blockName]; //获取块表记录的Id //打开块表记录 BlockTableRecord record = (BlockTableRecord)btrId.GetObject(OpenMode.ForRead); //添加可缩放性支持 if (record.Annotative == AnnotativeStates.True) { ObjectContextCollection contextCollection = db.ObjectContextManager.GetContextCollection("ACDB_ANNOTATIONSCALES"); ObjectContexts.AddContext(br, contextCollection.GetContext("1:1")); } blockRefId = space.AppendEntity(br); //在空间中加入创建的块参照 db.TransactionManager.AddNewlyCreatedDBObject(br, true); //通知事务处理加入创建的块参照 space.DowngradeOpen(); //为了安全,将块表状态改为读 return(blockRefId); //返回添加的块参照的Id }
/// <summary> /// 删除实体的缩放比例 /// </summary> /// <param name="entId">实体的Id</param> /// <param name="scaleNames">缩放比例名列表</param> public static void RemoveScale(this ObjectId entId, params string[] scaleNames) { //获取entId指示的实体对象 DBObject obj = entId.GetObject(OpenMode.ForRead); //如果实体对象支持注释缩放 if (obj.Annotative != AnnotativeStates.NotApplicable) { //获得对象所有的注释比例 List <ObjectContext> scales = entId.GetAllScales(); obj.UpgradeOpen();//切换实体为写的状态 //获取当前图形的对象比例管理器 ObjectContextManager ocm = obj.Database.ObjectContextManager; //获取当前图形的注释比例列表,名为ACDB_ANNOTATIONSCALES ObjectContextCollection occ = ocm.GetContextCollection("ACDB_ANNOTATIONSCALES"); //遍历需要设置的注释比例 foreach (string scaleName in scaleNames) { //获取名为scaleName的注释比例 ObjectContext scale = occ.GetContext(scaleName); //若不存在scaleName的注释比例,则结束本次循环 if (scale == null) { continue; } //删除名为scaleName的注释比例 ObjectContexts.RemoveContext(obj, scale); } obj.DowngradeOpen();//为了安全将实体切换为读的状态 } }
public DapperDbContext(IDbBuilder dbBuilder, ICommandBuilder commandBuilder, string conStr) { _dbBuilder = dbBuilder; CommandBuilder = commandBuilder; ConnectionString = conStr; ObjectCollection = new ObjectContextCollection(); }
/// <summary> /// 在AutoCAD图形中插入块参照 /// </summary> /// <param name="spaceId">块参照要加入的模型空间或图纸空间的Id</param> /// <param name="layer">块参照要加入的图层名</param> /// <param name="blockName">块参照所属的块名</param> /// <param name="position">插入点</param> /// <param name="scale">缩放比例</param> /// <param name="rotateAngle">旋转角度</param> /// <param name="attNameValues">属性的名称与取值</param> /// <returns>返回块参照的Id</returns> public static ObjectId InsertBlockReference(this ObjectId spaceId, string layer, string blockName, Point3d position, Scale3d scale, double rotateAngle) { DocumentLock docLock = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.LockDocument(); ObjectId blockRefId; Database db = spaceId.Database; BlockTable bt = (BlockTable)db.BlockTableId.GetObject(OpenMode.ForRead); if (!bt.Has(blockName)) { return(ObjectId.Null); } BlockTableRecord space = (BlockTableRecord)spaceId.GetObject(OpenMode.ForWrite); BlockReference br = new BlockReference(position, bt[blockName]); br.ScaleFactors = scale; br.Layer = layer; br.Rotation = rotateAngle; ObjectId btrId = bt[blockName]; BlockTableRecord record = (BlockTableRecord)btrId.GetObject(OpenMode.ForRead); if (record.Annotative == AnnotativeStates.True) { ObjectContextCollection contextCollection = db.ObjectContextManager.GetContextCollection("ACDB_ANNOTATIONSCALES"); ObjectContexts.AddContext(br, contextCollection.GetContext("1:1")); } blockRefId = space.AppendEntity(br); db.TransactionManager.AddNewlyCreatedDBObject(br, true); space.DowngradeOpen(); docLock.Dispose(); return(blockRefId); }
public CartogrammLabels(SimpleGride gride) { _gride = gride; TopRow = new List <TableField>(); BottomRow = new List <TableField>(); PreTopRow = new List <TableField>(); AmountTopRow = new List <TableField>(); PreBottomRow = new List <TableField>(); AmountBottomRow = new List <TableField>(); ObjectContextManager ocm = HostApplicationServices.WorkingDatabase.ObjectContextManager; ObjectContextCollection occ = ocm.GetContextCollection("ACDB_ANNOTATIONSCALES"); _scale = (AnnotationScale)occ.CurrentContext; _tableRowHeight /= _scale.Scale; _firstColumnWidth /= _scale.Scale; _preOrPostColumnWidth /= _scale.Scale; _tableTextHeight /= _scale.Scale; _grideTextHeight /= _scale.Scale; _volumeTextHeight /= _scale.Scale; _horizontalVector = gride.HorizontalVector; _verticalVector = gride.VerticalVector; }
public static ObjectId AppendBlockItem(Point3d insertPoint, ObjectId blockTableRecordId, List <string> attrTextValues, Matrix3d toWcsTransform) { ObjectId resBlockId = ObjectId.Null; Tools.StartTransaction(() => { Transaction trans = Tools.GetTopTransaction(); // Add a block reference to the model space BlockTableRecord ms = Tools.GetAcadBlockTableRecordModelSpace(OpenMode.ForWrite); BlockTableRecord btr = blockTableRecordId.GetObjectForRead <BlockTableRecord>(); BlockReference br = new BlockReference(insertPoint, blockTableRecordId); br.SetDatabaseDefaults(); br.TransformBy(toWcsTransform); ObjectContextManager ocm = btr.Database.ObjectContextManager; ObjectContextCollection occ = ocm.GetContextCollection("ACDB_ANNOTATIONSCALES"); if (btr.Annotative == AnnotativeStates.True) { br.AddContext(occ.CurrentContext); } resBlockId = ms.AppendEntity(br); trans.AddNewlyCreatedDBObject(br, true); // Add attributes from the block table record List <AttributeDefinition> attributes = GetAttributes(btr, trans); int i = 0; foreach (AttributeDefinition acAtt in attributes) { if (!acAtt.Constant) { using (AttributeReference acAttRef = new AttributeReference()) { acAttRef.SetAttributeFromBlock(acAtt, br.BlockTransform); if (attrTextValues != null) { acAttRef.TextString = attrTextValues[i++]; } else { acAttRef.TextString = acAtt.TextString; } br.AttributeCollection.AppendAttribute(acAttRef); trans.AddNewlyCreatedDBObject(acAttRef, true); } } } br.RecordGraphicsModified(true); }); return(resBlockId); }
public static ObjectId InsertBlock(Point3d anchorPoint, double Rotation, ObjectId BlockID) { // Get the current document and database Document acDoc = Application.DocumentManager.MdiActiveDocument; Database acCurDb = acDoc.Database; ObjectContextCollection occ = acCurDb.ObjectContextManager.GetContextCollection("ACDB_ANNOTATIONSCALES"); Transaction acTrans = acDoc.TransactionManager.TopTransaction; // Open the Block table for read BlockTable acBlkTbl = acTrans.GetObject(acCurDb.BlockTableId, OpenMode.ForRead) as BlockTable; BlockTableRecord blockDef = BlockID.GetObject(OpenMode.ForRead) as BlockTableRecord; // Open the Block table record Model space for write BlockTableRecord acBlkTblRec = acTrans.GetObject(acBlkTbl[BlockTableRecord.ModelSpace], OpenMode.ForWrite) as BlockTableRecord; // Insert the block into the current space using (BlockReference acBlkRef = new BlockReference(anchorPoint, BlockID)) { Matrix3d curUCSMatrix = Application.DocumentManager.MdiActiveDocument.Editor.CurrentUserCoordinateSystem; CoordinateSystem3d curUCS = curUCSMatrix.CoordinateSystem3d; acBlkRef.TransformBy(Matrix3d.Rotation(Rotation, curUCS.Zaxis, anchorPoint)); //For some unknown reason this is needed in Civil3D //TODO: Find reason below line is needed and fix it acBlkRef.TransformBy(Matrix3d.Scaling(1000, anchorPoint)); acBlkRef.AddContext(occ.GetContext("1:1")); acBlkTblRec = acTrans.GetObject(acCurDb.CurrentSpaceId, OpenMode.ForWrite) as BlockTableRecord; acBlkTblRec.AppendEntity(acBlkRef); acTrans.AddNewlyCreatedDBObject(acBlkRef, true); // AttributeDefinitions foreach (ObjectId id in blockDef) { DBObject obj = id.GetObject(OpenMode.ForRead); AttributeDefinition attDef = obj as AttributeDefinition; if ((attDef != null) && (!attDef.Constant)) { //This is a non-constant AttributeDefinition //Create a new AttributeReference using (AttributeReference attRef = new AttributeReference()) { attRef.SetAttributeFromBlock(attDef, acBlkRef.BlockTransform); attRef.TextString = "0"; //Add the AttributeReference to the BlockReference acBlkRef.AttributeCollection.AppendAttribute(attRef); acTrans.AddNewlyCreatedDBObject(attRef, true); } } } return(acBlkRef.ObjectId); } }
private void IncrementText(string styleName, string Justifi, string prefix, string suffix) { string startvalue = this.dlg.StartValue; int num = 0; Stack <ObjectId> objectIds = new Stack <ObjectId>(); Stack <string> strs = new Stack <string>(); ObjectId item = this.db.TextStyleTableId.GetObject <TextStyleTable>()[styleName]; bool flag = Justifi == "Left"; while (true) { using (DBText dBText = new DBText()) { dBText.Position = Point3d.Origin; dBText.TextStyleId = item; dBText.Justify = this.justify[Justifi]; dBText.Height = this.dlg.TextHeight; dBText.Rotation = this.dlg.TextRotation; dBText.TextString = string.Concat(prefix, startvalue, suffix); dBText.TransformBy(this.ed.CurrentUserCoordinateSystem); if (item.GetObject <TextStyleTableRecord>().Annotative == AnnotativeStates.True) { dBText.Annotative = AnnotativeStates.True; ObjectContextCollection contextCollection = this.db.ObjectContextManager.GetContextCollection("ACDB_ANNOTATIONSCALES"); Autodesk.AutoCAD.Internal.ObjectContexts.AddContext(dBText, contextCollection.CurrentContext); } TextJig textJig = new TextJig(dBText, num, flag, this.db); PromptResult promptResult = this.ed.Drag(textJig); if (promptResult.Status == PromptStatus.Keyword) { if (num != 0) { objectIds.Pop().GetObject <DBText>(OpenMode.ForWrite).Erase(); this.db.TransactionManager.QueueForGraphicsFlush(); startvalue = strs.Pop(); num--; } else { this.ed.WriteMessage(("\nNothing to undo !")); } } else if (promptResult.Status == PromptStatus.OK) { strs.Push(startvalue); objectIds.Push(this.db.GetCurrentSpace(OpenMode.ForWrite).Add(dBText)); this.db.TransactionManager.QueueForGraphicsFlush(); startvalue = this.Increment(startvalue); num++; } else { break; } } } this.dlg.txtValue.Text = startvalue; }
public void IncrementAttribute(BlockTableRecord TableRecord, int index, string prefix, string suffix) { string startValue = this.dlg.StartValue; int num = 0; Stack <ObjectId> objectIds = new Stack <ObjectId>(); Stack <string> strs = new Stack <string>(); while (true) { using (BlockReference blockRef = new BlockReference(Point3d.Origin, TableRecord.ObjectId)) { blockRef.Rotation = this.dlg.BlockRotation; blockRef.ScaleFactors = new Scale3d(this.dlg.BlockScale); blockRef.TransformBy(this.ed.CurrentUserCoordinateSystem); if (blockRef.Annotative == AnnotativeStates.True) { ObjectContextCollection contextCollection = this.db.ObjectContextManager.GetContextCollection("ACDB_ANNOTATIONSCALES"); Autodesk.AutoCAD.Internal.ObjectContexts.AddContext(blockRef, contextCollection.CurrentContext); } ObjectId objectId = this.db.GetCurrentSpace(OpenMode.ForWrite).Add(blockRef); blockRef.AddAttributeReferences(index, string.Concat(prefix, startValue, suffix)); BlockJig blockJig = new BlockJig(blockRef, num, TableRecord.GetAttributesTextInfos()); PromptResult promptResult = this.ed.Drag(blockJig); if (promptResult.Status == PromptStatus.Keyword) { blockRef.Erase(); if (num != 0) { objectIds.Pop().GetObject <BlockReference>(OpenMode.ForWrite).Erase(); this.db.TransactionManager.QueueForGraphicsFlush(); startValue = strs.Pop(); num--; } else { this.ed.WriteMessage("\nNothing to undo !"); } } else if (promptResult.Status == PromptStatus.OK) { this.db.TransactionManager.QueueForGraphicsFlush(); strs.Push(startValue); objectIds.Push(objectId); startValue = this.Increment(startValue); num++; } else { blockRef.Erase(); break; } } } this.dlg.txtValue.Text = startValue; }
private static void AddScale(DBObject ent, ObjectContext curScale, ObjectContextCollection occ) { ent.AddContext(curScale); foreach (var scale in occ) { if (scale.Name != curScale.Name && ent.HasContext(scale)) { ent.RemoveContext(scale); } } }
public void Scale() { Database db = HostApplicationServices.WorkingDatabase; DBText txt = DBText(Point3d.Origin, "深居浅出", 100); txt.Annotative = AnnotativeStates.True; ObjectContextManager cm = db.ObjectContextManager; ObjectContextCollection occ = cm.GetContextCollection("ACDB_ANNOTATIONSCALES"); foreach (ObjectContext oc in occ) { txt.AddContext(oc); } Circle cir = new Circle(new Point3d(265, 50, 0), Vector3d.ZAxis, 300); ToModelSpace(txt); ToModelSpace(cir); }
/// <summary> /// 为实体添加指定的注释比例 /// </summary> /// <param name="entId">实体的Id</param> /// <param name="scaleNames">注释比例名列表</param> public static void AttachScale(this ObjectId entId, params string[] scaleNames) { Database db = entId.Database; //获取entId指示的实体对象 DBObject obj = entId.GetObject(OpenMode.ForRead); //如果实体对象支持注释缩放 if (obj.Annotative != AnnotativeStates.NotApplicable) { //如果实体为块参照,则需要通过其所属的块表记录来设置可注释缩放 if (obj is BlockReference) { BlockReference br = obj as BlockReference; //打开对应的块表记录 BlockTableRecord btr = (BlockTableRecord)br.BlockTableRecord.GetObject(OpenMode.ForWrite); //设置块表记录为可注释缩放 btr.Annotative = AnnotativeStates.True; } //其它可注释缩放的实体,使其可注释缩放 else if (obj.Annotative == AnnotativeStates.False) { obj.Annotative = AnnotativeStates.True; } obj.UpgradeOpen();//切换实体为写的状态以添加注释比例 //获取当前图形的对象比例管理器 ObjectContextManager ocm = db.ObjectContextManager; //获取当前图形的注释比例列表,名为ACDB_ANNOTATIONSCALES ObjectContextCollection occ = ocm.GetContextCollection("ACDB_ANNOTATIONSCALES"); //遍历需要设置的注释比例 foreach (string scaleName in scaleNames) { //获取名为scaleName的注释比例 ObjectContext scale = occ.GetContext(scaleName); //若不存在scaleName的注释比例,则结束本次循环 if (scale == null) { continue; } //为实体添加名为scaleName的注释比例 ObjectContexts.AddContext(obj, scale); } obj.DowngradeOpen();//为了安全将实体切换为读的状态 } }
/// <summary> /// 为图形添加一个新的注释比例 /// </summary> /// <param name="db">图形数据库对象</param> /// <param name="scaleName">缩放比例名</param> /// <param name="paperUnits">缩放比例的图纸单位</param> /// <param name="drawingUnits">缩放比例的图形单位</param> /// <returns>返回添加的注释比例</returns> public static AnnotationScale AddScale(this Database db, string scaleName, double paperUnits, double drawingUnits) { AnnotationScale scale = null;//声明一个注释比例对象 //获取当前图形的对象比例管理器 ObjectContextManager ocm = db.ObjectContextManager; //获取当前图形的注释比例列表,名为ACDB_ANNOTATIONSCALES ObjectContextCollection occ = ocm.GetContextCollection("ACDB_ANNOTATIONSCALES"); //如果没有名为scaleName的注释比例 if (!occ.HasContext(scaleName)) { scale = new AnnotationScale(); //新建一个注释比例对象 scale.Name = scaleName; //注释比例名 scale.PaperUnits = paperUnits; //注释比例的图纸单位 scale.DrawingUnits = drawingUnits; //注释比例的图形单位 occ.AddContext(scale); //将scaleName注释比例添加比例列表中 } return(scale); //返回scaleName注释比例对象 }
private DBText _createDBText(Point3d alignmentPoint, double height) { ObjectContextManager ocm = HostApplicationServices.WorkingDatabase.ObjectContextManager; ObjectContextCollection occ = ocm.GetContextCollection("ACDB_ANNOTATIONSCALES"); AnnotationScale scale = (AnnotationScale)occ.CurrentContext; DBText text = new DBText(); text.SetDatabaseDefaults(); text.Height = height; /* * scale.DrawingUnits/ scale.PaperUnits;*/ text.Annotative = AnnotativeStates.False; text.Rotation = _textRotation; text.Position = Point3d.Origin; text.HorizontalMode = TextHorizontalMode.TextMid; text.VerticalMode = TextVerticalMode.TextVerticalMid; text.AlignmentPoint = alignmentPoint; //text.AddContext(occ.CurrentContext); text.AdjustAlignment(HostApplicationServices.WorkingDatabase); return(text); }
/// <summary> /// 获取实体拥有的所有缩放比例 /// </summary> /// <param name="entId">实体的Id</param> /// <returns>返回实体的缩放比例列表</returns> public static List <ObjectContext> GetAllScales(this ObjectId entId) { //声明一个列表对象,用于返回实体所拥有的所有的注释比例 List <ObjectContext> scales = new List <ObjectContext>(); DBObject obj = entId.GetObject(OpenMode.ForRead); if (obj.Annotative != AnnotativeStates.NotApplicable) { ObjectContextManager ocm = obj.Database.ObjectContextManager; ObjectContextCollection occ = ocm.GetContextCollection("ACDB_ANNOTATIONSCALES"); //遍历注释比例列表 foreach (ObjectContext oc in occ) { //如果实体拥有此注释比例 if (ObjectContexts.HasContext(obj, oc)) { scales.Add(oc);//将此注释比例添加到返回列表中 } } } return(scales);//返回实体所拥有的所有的注释比例 }
private void SetStyleAnnotative(DimStyleTableRecord[] resultStyleName, DBObject item, Dimension y) { AnnotationScale mainScale = new AnnotationScale(); ObjectContextManager ocm = targetDB.ObjectContextManager; double scale = 2.5 / (y.Dimscale * y.Dimtxt); double difference = 200; if (ocm != null) { ObjectContextCollection occ = ocm.GetContextCollection("ACDB_ANNOTATIONSCALES"); ObjectContext currentContext = occ.CurrentContext; foreach (ObjectContext context in occ) { double currentDifference = 200; AnnotationScale annotScale = (AnnotationScale)context; if (annotScale.Scale == scale) { mainScale = annotScale; break; } else { currentDifference = Math.Abs(scale - annotScale.Scale); if (currentDifference < difference) { difference = currentDifference; mainScale = annotScale; } } } SetStyleByType(resultStyleName, item, y); if (y.HasContext(currentContext)) { y.RemoveContext(currentContext); } y.AddContext(mainScale); y.Dimtxt = 2.5; } }
/// <summary> /// Type "CANNOSCALE" to get current scale /// </summary> /// <param name="scalename"></param> /// <returns></returns> public static AnnotationScale GetAnnoScale(string scalename) { if (scalename == "CANNOSCALE") { scalename = App.GetSystemVariable("CANNOSCALE").ToString(); } Document acDoc = App.DocumentManager.MdiActiveDocument; Database acCurDb = acDoc.Database; AnnotationScale asc = new AnnotationScale(); ObjectContextManager ocm = acCurDb.ObjectContextManager; if (ocm != null) { ObjectContextCollection occ = ocm.GetContextCollection("ACDB_ANNOTATIONSCALES"); if (occ != null) { asc = occ.GetContext(scalename) as AnnotationScale; } } return(asc); }
public void Generate() { Database acCurDb; acCurDb = Application.DocumentManager.MdiActiveDocument.Database; ObjectContextCollection occ = acCurDb.ObjectContextManager.GetContextCollection("ACDB_ANNOTATIONSCALES"); Transaction acTrans = acCurDb.TransactionManager.TopTransaction; //Centre line Curve c = acTrans.GetObject(ObjectId, OpenMode.ForRead) as Curve; //Offset it LayerTable acLyrTbl = acTrans.GetObject(acCurDb.LayerTableId, OpenMode.ForRead) as LayerTable; ObjectId current = acCurDb.Clayer; acCurDb.Clayer = acLyrTbl[Utilities.FoundationLayer]; // Open the Block table for read BlockTable acBlkTbl = acTrans.GetObject(acCurDb.BlockTableId, OpenMode.ForRead) as BlockTable; // Open the Block table record Model space for write BlockTableRecord acBlkTblRec = acTrans.GetObject(acBlkTbl[BlockTableRecord.ModelSpace], OpenMode.ForWrite) as BlockTableRecord; DBObjectCollection offsets = c.GetOffsetCurves(FoundationWidth / 2); DBObjectCollection offsets2 = c.GetOffsetCurves(-(FoundationWidth / 2)); foreach (Entity e in offsets) { acBlkTblRec.AppendEntity(e); acTrans.AddNewlyCreatedDBObject(e, true); e.LayerId = acCurDb.Clayer; PositiveFoundationId = e.ObjectId; } foreach (Entity e in offsets2) { acBlkTblRec.AppendEntity(e); acTrans.AddNewlyCreatedDBObject(e, true); e.LayerId = acCurDb.Clayer; NegativeFoundationId = e.ObjectId; } acCurDb.Clayer = current; //Tag it acCurDb.Clayer = acLyrTbl[Utilities.FoundationTextLayer]; //Add foundation tag Matrix3d curUCSMatrix = Application.DocumentManager.MdiActiveDocument.Editor.CurrentUserCoordinateSystem; CoordinateSystem3d curUCS = curUCSMatrix.CoordinateSystem3d; //Get lable point Point3d labelPoint3d = c.GetPointAtDist(c.GetDistanceAtParameter(c.EndParam) / 2); Point3d labelPoint = new Point3d(labelPoint3d.X, labelPoint3d.Y, 0); BlockTableRecord blockDef = acBlkTbl["FormationTag"].GetObject(OpenMode.ForRead) as BlockTableRecord; // Insert the block into the current space using (BlockReference acBlkRef = new BlockReference(labelPoint, acBlkTbl["FormationTag"])) { //Calculate Line Angle double y = c.EndPoint.Y - c.StartPoint.Y; double x = c.EndPoint.X - c.StartPoint.X; double angle = Math.Atan(Math.Abs(y) / Math.Abs(x)); if (angle >= Math.PI / 4) { acBlkRef.TransformBy(Matrix3d.Rotation(0, curUCS.Zaxis, labelPoint)); } else { acBlkRef.TransformBy(Matrix3d.Rotation(Math.PI / 2, curUCS.Zaxis, labelPoint)); } acBlkRef.AddContext(occ.GetContext("10:1")); acBlkTblRec = acTrans.GetObject(acCurDb.CurrentSpaceId, OpenMode.ForWrite) as BlockTableRecord; acBlkTblRec.AppendEntity(acBlkRef); acTrans.AddNewlyCreatedDBObject(acBlkRef, true); // AttributeDefinitions foreach (ObjectId id in blockDef) { DBObject obj = id.GetObject(OpenMode.ForRead); AttributeDefinition attDef = obj as AttributeDefinition; if ((attDef != null) && (!attDef.Constant)) { //This is a non-constant AttributeDefinition //Create a new AttributeReference using (AttributeReference attRef = new AttributeReference()) { attRef.SetAttributeFromBlock(attDef, acBlkRef.BlockTransform); attRef.TextString = Parent.FormationLevel.ToString("F3"); //Add the AttributeReference to the BlockReference acBlkRef.AttributeCollection.AppendAttribute(attRef); acTrans.AddNewlyCreatedDBObject(attRef, true); } } } FormationTagId = acBlkRef.ObjectId; } acCurDb.Clayer = current; }
private static void AddScaleAndRemoveOther(Entity ent, ObjectContext addScale, ObjectContextCollection occ) { ent.AddContext(addScale); foreach (var scale in occ) { if (addScale.Name != scale.Name && ent.HasContext(scale)) { ent.RemoveContext(scale); } } }
public BlockReference GetObject(Point3d position, List <string> attrTextValues) { if (this._blockId != ObjectId.Null) { _createBlockRecord(_name, _annotativeState, _origin, false); } BlockReference br = null; Tools.StartTransaction(() => { if (_blockRecordId != ObjectId.Null) { BlockTable bt = _db.BlockTableId.GetObjectForRead <BlockTable>(); BlockTableRecord ms = bt[BlockTableRecord.ModelSpace].GetObjectForWrite <BlockTableRecord>(); BlockTableRecord btr = _blockRecordId.GetObjectForRead <BlockTableRecord>(); br = new BlockReference(position, _blockRecordId); ObjectContextManager ocm = btr.Database.ObjectContextManager; ObjectContextCollection occ = ocm.GetContextCollection("ACDB_ANNOTATIONSCALES"); if (btr.Annotative == AnnotativeStates.True) { br.AddContext(occ.CurrentContext); } ObjectId brId = ms.AppendEntity(br); _db.TransactionManager.TopTransaction.AddNewlyCreatedDBObject(br, true); // Add attributes from the block table record List <AttributeDefinition> attributes = btr.GetAttributes(); int i = 0; foreach (AttributeDefinition acAtt in attributes) { if (!acAtt.Constant) { using (AttributeReference acAttRef = new AttributeReference()) { //acAttRef.RecordGraphicsModified(true); acAttRef.SetAttributeFromBlock(acAtt, br.BlockTransform); //acAttRef.Position = acAtt.Position.TransformBy(br.BlockTransform); acAttRef.TextString = attrTextValues[i++]; //if (acAtt.Annotative == AnnotativeStates.True) //acAttRef.AddContext(occ.CurrentContext); br.AttributeCollection.AppendAttribute(acAttRef); _db.TransactionManager.TopTransaction.AddNewlyCreatedDBObject(acAttRef, true); } } } _insertPoint = position; _blockId = br.Id; } }); return(br); }
public static void testAttributedBlockInsert() { Document doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument; Database db = doc.Database; Editor ed = doc.Editor; // change block name to your suit PromptEntityOptions pEnOpt = new PromptEntityOptions("\nPick Block Reference:"); pEnOpt.SetRejectMessage("\nObject Not Block Reference"); pEnOpt.AddAllowedClass(typeof(BlockReference), true); PromptEntityResult pEnRes = ed.GetEntity(pEnOpt); ObjectId EntId = pEnRes.ObjectId; //PromptResult pr = ed.GetString("\nType Block Name: "); //string blockName = pr.StringResult; string blockName = null; BlockReference UserBlockref = null; using (Transaction trans = db.TransactionManager.StartTransaction()) { UserBlockref = (BlockReference)trans.GetObject(EntId, OpenMode.ForRead); blockName = UserBlockref.Name; } Matrix3d ucs = ed.CurrentUserCoordinateSystem; //get current UCS matrix try { using (Transaction tr = db.TransactionManager.StartTransaction()) { // to force update drawing screen doc.TransactionManager.EnableGraphicsFlush(true); BlockTable bt = (BlockTable)tr.GetObject(db.BlockTableId, OpenMode.ForWrite); // if the block table doesn't already exists, exit if (!bt.Has(blockName)) { Autodesk.AutoCAD.ApplicationServices.Application.ShowAlertDialog("Block " + blockName + " does not exist."); return; } // insert the block in the current space PromptPointResult ppr = ed.GetPoint("\nSpecify insertion point: "); if (ppr.Status != PromptStatus.OK) { return; } DBObjectCollection dbobjcoll = ed.TraceBoundary(ppr.Value, false); Double area = 0; try { if (dbobjcoll.Count > 0) { BlockTableRecord blockTableRecmSpace = (BlockTableRecord)tr.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForRead); ObjectIdCollection traceObjIds = new ObjectIdCollection(); foreach (DBObject obj in dbobjcoll) { Entity EntTrace = obj as Entity; if (EntTrace != null) { if (EntTrace is Polyline) { Polyline p = (Polyline)EntTrace; if (p.Closed) { area = p.Area; } } if (EntTrace is Line) { Line Ln = (Line)EntTrace; if (Ln.Closed) { area = Ln.Area; } } } } } } catch { throw; } string presisi = "#"; switch (db.Auprec) { case 0: presisi = "#"; break; case 1: presisi = "#0.0"; break; case 2: presisi = "#0.00"; break; case 3: presisi = "#0.000"; break; case 4: presisi = "#0.0000"; break; case 5: presisi = "#0.00000"; break; default: presisi = "#0.00"; break; } valueAreaBoundary = area.ToString(presisi); BlockTableRecord btr = (BlockTableRecord)tr.GetObject(db.CurrentSpaceId, OpenMode.ForWrite); ObjectContextCollection occ = db.ObjectContextManager.GetContextCollection("ACDB_ANNOTATIONSCALES"); List<string> ListTag = new List<string>(); List<string> ListString = new List<string>(); Point3d pt = ppr.Value; BlockReference bref = new BlockReference(pt, bt[blockName]); Dictionary<string, string> dic = GetAttributDef(bref.BlockTableRecord, tr); foreach (KeyValuePair<string, string> item in dic) { ListTag.Add(item.Key.ToUpper().ToString()); // string[] info = item.Value.Split('|'); } formUserInputAttribut frmInput = new formUserInputAttribut(); IntPtr handle = AcAp.MainWindow.Handle; if (frmInput.ShowDialog(ListTag) == System.Windows.Forms.DialogResult.OK) { ListString.AddRange(frmInput.InputString); } else { return; } bref.Rotation = frmInput.UseRotation ? UserBlockref.Rotation : 0.0; bref.TransformBy(ucs); bref.AddContext(occ.CurrentContext); //add blockreference to current space btr.AppendEntity(bref); tr.AddNewlyCreatedDBObject(bref, true); // set attributes to desired values ApplyAttibutes(db, tr, bref, ListTag, ListString); bref.RecordGraphicsModified(true); // to force updating a block reference tr.TransactionManager.QueueForGraphicsFlush(); tr.Commit(); } } catch (Autodesk.AutoCAD.Runtime.Exception ex) { Autodesk.AutoCAD.ApplicationServices.Application.ShowAlertDialog(ex.Message); } finally { // Autodesk.AutoCAD.ApplicationServices.Application.ShowAlertDialog("Pokey") } }
public static ObjectId AddBlockRefToModelSpace(ObjectId blockTableRecordId, List <string> attrTextValues, Point3d location, Matrix3d matrix, Transaction trans, bool commit) { // Add a block reference to the model space BlockTableRecord ms = Tools.GetAcadBlockTableRecordModelSpace(trans, OpenMode.ForWrite); BlockTableRecord btr = (BlockTableRecord)trans.GetObject(blockTableRecordId, OpenMode.ForRead); BlockReference br = new BlockReference(location, blockTableRecordId); br.TransformBy(matrix); ObjectContextManager ocm = btr.Database.ObjectContextManager; ObjectContextCollection occ = ocm.GetContextCollection("ACDB_ANNOTATIONSCALES"); if (btr.Annotative == AnnotativeStates.True) { br.AddContext(occ.CurrentContext); } //br.RecordGraphicsModified(true); ObjectId brId = ms.AppendEntity(br); trans.AddNewlyCreatedDBObject(br, true); // Add attributes from the block table record List <AttributeDefinition> attributes = GetAttributes(btr, trans); int i = 0; foreach (AttributeDefinition acAtt in attributes) { if (!acAtt.Constant) { using (AttributeReference acAttRef = new AttributeReference()) { //acAttRef.RecordGraphicsModified(true); acAttRef.SetAttributeFromBlock(acAtt, br.BlockTransform); //acAttRef.Position = acAtt.Position.TransformBy(br.BlockTransform); if (attrTextValues != null) { acAttRef.TextString = attrTextValues[i++]; } else { acAttRef.TextString = acAtt.TextString; } //if (acAtt.Annotative == AnnotativeStates.True) //acAttRef.AddContext(occ.CurrentContext); br.AttributeCollection.AppendAttribute(acAttRef); trans.AddNewlyCreatedDBObject(acAttRef, true); } } // Change the attribute definition to be displayed as backwards //acAtt.UpgradeOpen(); //acAtt.IsMirroredInX = true; //acAtt.IsMirroredInY = false; } br.RecordGraphicsModified(true); if (commit) { trans.Commit(); } return(brId); }
public static void TagFoundations(List <Curve> lines, Plot p) { Database acCurDb; acCurDb = Application.DocumentManager.MdiActiveDocument.Database; ObjectContextCollection occ = acCurDb.ObjectContextManager.GetContextCollection("ACDB_ANNOTATIONSCALES"); using (Transaction acTrans = acCurDb.TransactionManager.StartTransaction()) { LayerTable acLyrTbl = acTrans.GetObject(acCurDb.LayerTableId, OpenMode.ForRead) as LayerTable; ObjectId current = acCurDb.Clayer; acCurDb.Clayer = acLyrTbl[Main.FoundationTextLayer]; // Open the Block table for read BlockTable acBlkTbl; acBlkTbl = acTrans.GetObject(acCurDb.BlockTableId, OpenMode.ForRead) as BlockTable; ObjectId blkRecId = ObjectId.Null; if (!acBlkTbl.Has("FormationTag")) { Main.LoadBlocks(); } foreach (Curve c in lines) { Matrix3d curUCSMatrix = Application.DocumentManager.MdiActiveDocument.Editor.CurrentUserCoordinateSystem; CoordinateSystem3d curUCS = curUCSMatrix.CoordinateSystem3d; //Get lable point Point3d labelPoint3d = c.GetPointAtDist(c.GetDistanceAtParameter(c.EndParam) / 2); Point3d labelPoint = new Point3d(labelPoint3d.X, labelPoint3d.Y, 0); // Insert the block into the current space using (BlockReference acBlkRef = new BlockReference(labelPoint, acBlkTbl["FormationTag"])) { //Calculate Line Angle double y = c.EndPoint.Y - c.StartPoint.Y; double x = c.EndPoint.X - c.StartPoint.X; double angle = Math.Atan(Math.Abs(y) / Math.Abs(x)); if (angle >= Math.PI / 2) { acBlkRef.TransformBy(Matrix3d.Rotation(0, curUCS.Zaxis, labelPoint)); } else { acBlkRef.TransformBy(Matrix3d.Rotation(Math.PI / 2, curUCS.Zaxis, labelPoint)); } acBlkRef.AddContext(occ.GetContext("10:1")); //Set value AttributeCollection attCol = acBlkRef.AttributeCollection; foreach (ObjectId attId in attCol) { AttributeReference att = acTrans.GetObject(attId, OpenMode.ForRead, false) as AttributeReference; if (att.Tag == "LEVEL") { att.UpgradeOpen(); att.TextString = p.FormationLevel.ToString(); } } BlockTableRecord acCurSpaceBlkTblRec; acCurSpaceBlkTblRec = acTrans.GetObject(acCurDb.CurrentSpaceId, OpenMode.ForWrite) as BlockTableRecord; acCurSpaceBlkTblRec.AppendEntity(acBlkRef); acTrans.AddNewlyCreatedDBObject(acBlkRef, true); } } acCurDb.Clayer = current; acTrans.Commit(); } }