public static void ApplyAttributes(Database db, QuickTransaction tr, BlockReference bref) { if (bref == null) { return; } var _brec = tr.GetObject(bref.BlockTableRecord, OpenMode.ForRead); var btrec = _brec as BlockTableRecord; if (btrec == null) { return; } if (btrec.HasAttributeDefinitions) { var atcoll = bref.AttributeCollection; foreach (var subid in btrec) { var ent = (Entity)subid.GetObject(OpenMode.ForRead); var attDef = ent as AttributeDefinition; if (attDef != null) { var attRef = new AttributeReference(); attRef.SetDatabaseDefaults(); //optional attRef.SetAttributeFromBlock(attDef, bref.BlockTransform); attRef.Position = attDef.Position.TransformBy(bref.BlockTransform); attRef.Tag = attDef.Tag; attRef.AdjustAlignment(db); atcoll.AppendAttribute(attRef); tr.AddNewlyCreatedDBObject(attRef, true); } } } }
private static void ApplyAttibutes(Database db, Transaction tr, BlockReference bref, List<string> listTags, List<string> listValues) { BlockTableRecord btr = (BlockTableRecord)tr.GetObject(bref.BlockTableRecord, OpenMode.ForRead); foreach (ObjectId attId in btr) { Entity ent = (Entity)tr.GetObject(attId, OpenMode.ForRead); if (ent is AttributeDefinition) { AttributeDefinition attDef = (AttributeDefinition)ent; AttributeReference attRef = new AttributeReference(); attRef.SetAttributeFromBlock(attDef, bref.BlockTransform); bref.AttributeCollection.AppendAttribute(attRef); tr.AddNewlyCreatedDBObject(attRef, true); if (listTags.Contains(attDef.Tag.ToUpper())) { ListStringComparer lsc = new ListStringComparer(); int found = listTags.BinarySearch(attDef.Tag.ToUpper(), lsc); int index = listTags.FindIndex(s => s.Contains(attDef.Tag.ToUpper())); string strtemp = listValues[index]; if (index >= 0) { attRef.TextString = listValues[index]; attRef.AdjustAlignment(db); } } } } }
public static AttributeReference AddAttributeReferences(this BlockReference br, int index, string value) { BlockTableRecord obj = br.BlockTableRecord.GetObject <BlockTableRecord>(); Transaction topTransaction = br.Database.TransactionManager.TopTransaction; AttributeReference attributeReference = null; AttributeDefinition[] array = obj.GetObjects <AttributeDefinition>().ToArray <AttributeDefinition>(); for (int i = 0; i < (int)array.Length; i++) { AttributeDefinition attributeDefinition = array[i]; AttributeReference attributeReference1 = new AttributeReference(); attributeReference1.SetAttributeFromBlock(attributeDefinition, br.BlockTransform); Point3d position = attributeDefinition.Position; attributeReference1.Position = position.TransformBy(br.BlockTransform); if (attributeDefinition.Justify != AttachmentPoint.BaseLeft) { position = attributeDefinition.AlignmentPoint; attributeReference1.AlignmentPoint = position.TransformBy(br.BlockTransform); attributeReference1.AdjustAlignment(br.Database); } if (attributeReference1.IsMTextAttribute) { attributeReference1.UpdateMTextAttribute(); } if (i == index) { attributeReference1.TextString = value; attributeReference = attributeReference1; } br.AttributeCollection.AppendAttribute(attributeReference1); topTransaction.AddNewlyCreatedDBObject(attributeReference1, true); } return(attributeReference); }
/// <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, Dictionary <string, string> attNameValues) { 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); ObjectId btrId = bt[blockName];//获取块表记录的Id //打开块表记录 BlockTableRecord record = (BlockTableRecord)btrId.GetObject(OpenMode.ForRead); //创建一个块参照并设置插入点 BlockReference br = new BlockReference(position, bt[blockName]); br.ScaleFactors = scale; //设置块参照的缩放比例 br.Layer = layer; //设置块参照的层名 br.Rotation = rotateAngle; //设置块参照的旋转角度 space.AppendEntity(br); //为了安全,将块表状态改为读 //判断块表记录是否包含属性定义 if (record.HasAttributeDefinitions) { //若包含属性定义,则遍历属性定义 foreach (ObjectId id in record) { //检查是否是属性定义 AttributeDefinition attDef = id.GetObject(OpenMode.ForRead) as AttributeDefinition; if (attDef != null) { //创建一个新的属性对象 AttributeReference attribute = new AttributeReference(); //从属性定义获得属性对象的对象特性 attribute.SetAttributeFromBlock(attDef, br.BlockTransform); //设置属性对象的其它特性 attribute.Position = attDef.Position.TransformBy(br.BlockTransform); attribute.Rotation = attDef.Rotation; attribute.AdjustAlignment(db); //判断是否包含指定的属性名称 if (attNameValues.ContainsKey(attDef.Tag.ToUpper())) { //设置属性值 attribute.TextString = attNameValues[attDef.Tag.ToUpper()].ToString(); } //向块参照添加属性对象 br.AttributeCollection.AppendAttribute(attribute); db.TransactionManager.AddNewlyCreatedDBObject(attribute, true); } } } db.TransactionManager.AddNewlyCreatedDBObject(br, true); return(br.ObjectId);//返回添加的块参照的Id }
public ObjectId CreateEmployee(string name, string division, double salary, Point3d position) { var db = HostApplicationServices.WorkingDatabase; var blkId = CreateBlkDefinition(); ObjectId idIns = ObjectId.Null; using (var trans = db.TransactionManager.StartTransaction()) { var ins = new BlockReference(position, blkId); var curBtr = trans.GetObject(db.CurrentSpaceId, OpenMode.ForWrite) as BlockTableRecord; idIns = curBtr.AppendEntity(ins); trans.AddNewlyCreatedDBObject(ins, true); var empBlk = trans.GetObject(blkId, OpenMode.ForRead) as BlockTableRecord; foreach (var id in empBlk) { if (trans.GetObject(id, OpenMode.ForRead, false) is AttributeDefinition attDef) { var attRef = new AttributeReference(); attRef.SetPropertiesFrom(attDef); attRef.Position = position; attRef.Height = attDef.Height; attRef.Rotation = attDef.Rotation; attRef.Tag = attDef.Tag; attRef.TextString = name; attRef.HorizontalMode = attDef.HorizontalMode; attRef.VerticalMode = attDef.VerticalMode; attRef.AlignmentPoint = position; attRef.AdjustAlignment(db); ins.AttributeCollection.AppendAttribute(attRef); trans.AddNewlyCreatedDBObject(attRef, true); } } ins.CreateExtensionDictionary(); var extDict = trans.GetObject(ins.ExtensionDictionary, OpenMode.ForWrite) as DBDictionary; var data = new ResultBuffer( new TypedValue((int)DxfCode.Text, name), new TypedValue((int)DxfCode.Real, salary), new TypedValue((int)DxfCode.Text, division)); CreateXRecWithData(trans, extDict, "EmploeeInfo", data); trans.Commit(); } return(idIns); }
public static void ApplyAttibutes(Database db, Transaction tr, BlockReference bref, string attrValue) { BlockTableRecord btr = (BlockTableRecord)tr.GetObject(bref.BlockTableRecord, OpenMode.ForRead); int i = 0; foreach (ObjectId attId in btr) { Entity ent = (Entity)tr.GetObject(attId, OpenMode.ForRead); if (ent is AttributeDefinition) { AttributeDefinition attDef = (AttributeDefinition)ent; AttributeReference attRef = new AttributeReference(); attRef.SetAttributeFromBlock(attDef, bref.BlockTransform); bref.AttributeCollection.AppendAttribute(attRef); tr.AddNewlyCreatedDBObject(attRef, true); attRef.TextString = attrValue.ToString(); attRef.AdjustAlignment(db); } } }
/// <summary> /// Copies attributes to BlockReference from "BlockDefinition" /// </summary> /// <param name="acBlkRef"></param> /// <param name="blockDefinition"></param> /// <param name="tr"></param> private void CreateBlockRefenceAttributes(BlockReference acBlkRef, BlockTableRecord blockDefinition, Transaction tr) { // copy/create attribute references foreach (var bdEntityObjectId in blockDefinition) { var ad = tr.GetObject(bdEntityObjectId, OpenMode.ForRead) as AttributeDefinition; if (ad == null) { continue; } using (var ar = new AttributeReference()) { ar.SetDatabaseDefaults(_db); ar.SetAttributeFromBlock(ad, acBlkRef.BlockTransform); ar.TextString = ad.TextString; // set default value, copied from AttributeDefinition ar.AdjustAlignment(HostApplicationServices.WorkingDatabase); acBlkRef.AttributeCollection.AppendAttribute(ar); tr.AddNewlyCreatedDBObject(ar, true); } } }
//INSERT DYNAMIC BLOCK INTO DATABASE public static Dictionary <ObjectId, ObjectId> InsertDynamicBlock(string blockName, Database db, ref BlockReference bref) { Dictionary <ObjectId, ObjectId> atts = new System.Collections.Generic.Dictionary <ObjectId, ObjectId>(); using (Transaction tr = db.TransactionManager.StartTransaction()) { BlockTable bt = (BlockTable)tr.GetObject(db.BlockTableId, OpenMode.ForWrite); BlockTableRecord btr = (BlockTableRecord)tr.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForWrite); if (bt.Has(blockName)) { bref = new BlockReference(Point3d.Origin, bt[blockName]); btr.AppendEntity(bref); tr.AddNewlyCreatedDBObject(bref, true); BlockTableRecord brefRec = (BlockTableRecord)tr.GetObject(bref.BlockTableRecord, OpenMode.ForRead); if (brefRec.HasAttributeDefinitions) { foreach (ObjectId id in btr) { DBObject dbObj = tr.GetObject(id, OpenMode.ForWrite); if (dbObj is AttributeDefinition) { AttributeDefinition newAttriDef = (AttributeDefinition)dbObj; AttributeReference attRef = new AttributeReference(); attRef.SetAttributeFromBlock(newAttriDef, bref.BlockTransform); attRef.AdjustAlignment(bref.Database); bref.AttributeCollection.AppendAttribute(attRef); tr.AddNewlyCreatedDBObject(attRef, true); atts.Add(attRef.ObjectId, id); } } } } tr.Commit(); } return(atts); }
protected override bool Update() { if (bref is BlockReference) { BlockReference brf = (BlockReference)bref; brf.Position = insertPoint; if (atts != null) { foreach (ObjectId id in brf.AttributeCollection) { AttributeReference attRef = (AttributeReference)tr.GetObject(id, OpenMode.ForRead); if (attRef != null) { attRef.UpgradeOpen(); AttributeDefinition adef = (AttributeDefinition)tr.GetObject(atts[attRef.ObjectId], OpenMode.ForRead); attRef.SetAttributeFromBlock(adef, brf.BlockTransform); attRef.AdjustAlignment(brf.Database); } } } } return(true); }
addBlockRef(string strName, string strTopNum, string strTopTxt, string strBotNum, string strBotTxt, Point3d pnt3dIns, double dblRotation) { Database DB = BaseObjs._db; Editor ED = BaseObjs._editor; ObjectId blkID = ObjectId.Null; BlockTableRecord Btrx = null; using (Transaction tr = BaseObjs.startTransactionDb()) { BlockTable BT = (BlockTable)DB.BlockTableId.GetObject(OpenMode.ForRead); if (!BT.Has(strName)) { blkID = insBlockRef(@"R:\Tset\Block\", "GradeTag.dwg"); Btrx = (BlockTableRecord)blkID.GetObject(OpenMode.ForRead); Btrx.UpgradeOpen(); Btrx.Name = "GradeTag"; Btrx.DowngradeOpen(); } else { Btrx = (BlockTableRecord)BT[strName].GetObject(OpenMode.ForRead); } //---> debug only foreach (ObjectId objID in Btrx) { Entity ENT = (Entity)objID.GetObject(OpenMode.ForRead); AttributeDefinition AD = ENT as AttributeDefinition; if (AD != null) { ED.WriteMessage(string.Format("\n{0}", AD.Tag)); } }//<--- debug only BlockTableRecord Btr = (BlockTableRecord)DB.CurrentSpaceId.GetObject(OpenMode.ForWrite); using (Btr) { BlockReference BR = new BlockReference(pnt3dIns, Btrx.ObjectId); using (BR) { Matrix3d UCSMatrix = ED.CurrentUserCoordinateSystem; CoordinateSystem3d UCS = UCSMatrix.CoordinateSystem3d; Matrix3d MAT3d = new Matrix3d(); MAT3d = Matrix3d.Rotation(dblRotation, UCS.Zaxis, pnt3dIns); BR.TransformBy(MAT3d); BR.ScaleFactors = new Scale3d(1, 1, 1); Btr.AppendEntity(BR); tr.AddNewlyCreatedDBObject(BR, true); BlockTableRecord Btratt = (BlockTableRecord)BR.BlockTableRecord.GetObject(OpenMode.ForRead); using (Btratt) { Autodesk.AutoCAD.DatabaseServices.AttributeCollection ATTcol = BR.AttributeCollection; foreach (ObjectId subID in Btratt) { Entity ENT = (Entity)subID.GetObject(OpenMode.ForRead); AttributeDefinition AD = ENT as AttributeDefinition; if (AD != null) { AttributeReference AR = new AttributeReference(); AR.SetPropertiesFrom(AD); AR.SetAttributeFromBlock(AD, BR.BlockTransform); AR.Visible = AD.Visible; AR.HorizontalMode = AD.HorizontalMode; AR.VerticalMode = AD.VerticalMode; AR.Rotation = AD.Rotation; AR.TextStyleId = AD.TextStyleId; AR.Position = AD.Position + pnt3dIns.GetAsVector(); AR.Tag = AD.Tag; AR.FieldLength = AD.FieldLength; AR.AdjustAlignment(DB); if (AR.Tag == "TOPNUM") { AR.TextString = strTopNum; } if (AR.Tag == "TOPTXT") { AR.TextString = strTopTxt; } if (AR.Tag == "BOTNUM") { AR.TextString = strBotNum; } if (AR.Tag == "BOTTXT") { AR.TextString = strBotTxt; } AR.Position = AD.Position.TransformBy(BR.BlockTransform); ATTcol.AppendAttribute(AR); tr.AddNewlyCreatedDBObject(AR, true); } // end if } //end foreach } BR.DowngradeOpen(); } Btr.DowngradeOpen(); } // BT.DowngradeOpen (); tr.Commit(); } return(true); }
private void UpdateBlock() { Autodesk.AutoCAD.ApplicationServices.Document doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument; Autodesk.AutoCAD.DatabaseServices.Database db = doc.Database; Matrix3d ucs2wcs = AcadUtility.AcadGraphics.UcsToWcs; Point3d pBaseWorld = mpBase.TransformBy(ucs2wcs); Point3d pTextWorld = mpText.TransformBy(ucs2wcs); BlockReference bref = Entity as BlockReference; bref.TransformBy(lastTransform.Inverse()); for (int i = 0; i < bref.AttributeCollection.Count; i++) { AttributeReference attRef = bref.AttributeCollection[i].GetObject(OpenMode.ForWrite) as AttributeReference; string text = attRef.TextString; attRef.SetAttributeFromBlock(mAttDict[attRef], bref.BlockTransform); attRef.TextString = text; attRef.AdjustAlignment(db); } bref.Position = pTextWorld; double scale = Math.Abs(bref.ScaleFactors[0]); // Mirror block if text is to the left of base point if (mpText.X < mpBase.X) { using (Line3d mirrorLine = new Line3d(bref.Position, bref.Position + ucs2wcs.CoordinateSystem3d.Yaxis)) { Matrix3d mirroring = Matrix3d.Mirroring(mirrorLine); bref.TransformBy(mirroring); lastTransform = mirroring; } for (int i = 0; i < bref.AttributeCollection.Count; i++) { AttributeReference attRef = bref.AttributeCollection[i].GetObject(OpenMode.ForWrite) as AttributeReference; string text = attRef.TextString; attRef.SetAttributeFromBlock(mAttDict[attRef], bref.BlockTransform); attRef.TextString = text; Extents3d ex = attRef.GeometricExtents; Point3d midPoint = new Point3d((ex.MinPoint.X + ex.MaxPoint.X) / 2, (ex.MinPoint.Y + ex.MaxPoint.Y) / 2, (ex.MinPoint.Z + ex.MaxPoint.Z) / 2); using (Line3d mirrorLine = new Line3d(midPoint, midPoint + ucs2wcs.CoordinateSystem3d.Yaxis)) { Matrix3d mirroring = Matrix3d.Mirroring(mirrorLine); attRef.TransformBy(mirroring); } attRef.AdjustAlignment(db); } } else { lastTransform = Matrix3d.Identity; } IntegerCollection vpNumbers = AcadUtility.AcadGraphics.GetActiveViewportNumbers(); if (line == null) { line = new Line(); TransientManager.CurrentTransientManager.AddTransient(line, TransientDrawingMode.DirectShortTerm, 0, vpNumbers); } line.StartPoint = pBaseWorld; line.EndPoint = pTextWorld; TransientManager.CurrentTransientManager.UpdateTransient(line, vpNumbers); }
/// <summary> /// Синхронизация вхождений блоков с их определением /// via http://sites.google.com/site/bushmansnetlaboratory/moi-zametki/attsynch /// </summary> /// <param name="btr">Запись таблицы блоков, принятая за определение блока</param> /// <param name="directOnly">Следует ли искать только на верхнем уровне, или же нужно /// анализировать и вложенные вхождения, т.е. следует ли рекурсивно обрабатывать блок в блоке: /// true - только верхний; false - рекурсивно проверять вложенные блоки.</param> /// <param name="removeSuperfluous"> /// Следует ли во вхождениях блока удалять лишние атрибуты (те, которых нет в определении блока).</param> /// <param name="setAttDefValues"> /// Следует ли всем атрибутам, во вхождениях блока, назначить текущим значением значение по умолчанию.</param> public static void AttSync(this BlockTableRecord btr, bool directOnly, bool removeSuperfluous, bool setAttDefValues) { Database db = btr.Database; // using (Bushman.AutoCAD.DatabaseServices.WorkingDatabaseSwitcher wdb = new Bushman.AutoCAD.DatabaseServices.WorkingDatabaseSwitcher(db)) { using (Transaction t = db.TransactionManager.StartTransaction()) { BlockTable bt = (BlockTable)t.GetObject(db.BlockTableId, OpenMode.ForRead); //Получаем все определения атрибутов из определения блока IEnumerable <AttributeDefinition> attdefs = btr.Cast <ObjectId>() .Where(n => n.ObjectClass.Name == "AcDbAttributeDefinition") .Select(n => (AttributeDefinition)t.GetObject(n, OpenMode.ForRead)) .Where(n => !n.Constant);//Исключаем константные атрибуты, т.к. для них AttributeReference не создаются. //В цикле перебираем все вхождения искомого определения блока foreach (ObjectId brId in btr.GetBlockReferenceIds(directOnly, false)) { BlockReference br = (BlockReference)t.GetObject(brId, OpenMode.ForWrite); //Проверяем имена на соответствие. В том случае, если вхождение блока "A" вложено в определение блока "B", //то вхождения блока "B" тоже попадут в выборку. Нам нужно их исключить из набора обрабатываемых объектов //- именно поэтому проверяем имена. if (br.Name != btr.Name) { continue; } //Получаем все атрибуты вхождения блока IEnumerable <AttributeReference> attrefs = br.AttributeCollection.Cast <ObjectId>() .Select(n => (AttributeReference)t.GetObject(n, OpenMode.ForWrite)); //Тэги существующих определений атрибутов IEnumerable <string> dtags = attdefs.Select(n => n.Tag); //Тэги существующих атрибутов во вхождении IEnumerable <string> rtags = attrefs.Select(n => n.Tag); //Если требуется - удаляем те атрибуты, для которых нет определения //в составе определения блока if (removeSuperfluous) { foreach (AttributeReference attref in attrefs.Where(n => rtags .Except(dtags).Contains(n.Tag))) { attref.Erase(true); } } //Свойства существующих атрибутов синхронизируем со свойствами их определений foreach (AttributeReference attref in attrefs.Where(n => dtags .Join(rtags, a => a, b => b, (a, b) => a).Contains(n.Tag))) { AttributeDefinition ad = attdefs.First(n => n.Tag == attref.Tag); //Метод SetAttributeFromBlock, используемый нами далее в коде, сбрасывает //текущее значение многострочного атрибута. Поэтому запоминаем это значение, //чтобы восстановить его сразу после вызова SetAttributeFromBlock. string value = attref.TextString; attref.SetAttributeFromBlock(ad, br.BlockTransform); //Восстанавливаем значение атрибута attref.TextString = value; if (attref.IsMTextAttribute) { } //Если требуется - устанавливаем для атрибута значение по умолчанию if (setAttDefValues) { attref.TextString = ad.TextString; } attref.AdjustAlignment(db); } //Если во вхождении блока отсутствуют нужные атрибуты - создаём их IEnumerable <AttributeDefinition> attdefsNew = attdefs.Where(n => dtags .Except(rtags).Contains(n.Tag)); foreach (AttributeDefinition ad in attdefsNew) { AttributeReference attref = new AttributeReference(); attref.SetAttributeFromBlock(ad, br.BlockTransform); attref.AdjustAlignment(db); br.AttributeCollection.AppendAttribute(attref); t.AddNewlyCreatedDBObject(attref, true); } } btr.UpdateAnonymousBlocks(); t.Commit(); } //Если это динамический блок if (btr.IsDynamicBlock) { using (Transaction t = db.TransactionManager.StartTransaction()) { foreach (ObjectId id in btr.GetAnonymousBlockIds()) { BlockTableRecord _btr = (BlockTableRecord)t.GetObject(id, OpenMode.ForWrite); //Получаем все определения атрибутов из оригинального определения блока IEnumerable <AttributeDefinition> attdefs = btr.Cast <ObjectId>() .Where(n => n.ObjectClass.Name == "AcDbAttributeDefinition") .Select(n => (AttributeDefinition)t.GetObject(n, OpenMode.ForRead)); //Получаем все определения атрибутов из определения анонимного блока IEnumerable <AttributeDefinition> attdefs2 = _btr.Cast <ObjectId>() .Where(n => n.ObjectClass.Name == "AcDbAttributeDefinition") .Select(n => (AttributeDefinition)t.GetObject(n, OpenMode.ForWrite)); //Определения атрибутов анонимных блоков следует синхронизировать //с определениями атрибутов основного блока //Тэги существующих определений атрибутов IEnumerable <string> dtags = attdefs.Select(n => n.Tag); IEnumerable <string> dtags2 = attdefs2.Select(n => n.Tag); //1. Удаляем лишние foreach (AttributeDefinition attdef in attdefs2.Where(n => !dtags.Contains(n.Tag))) { attdef.Erase(true); } //2. Синхронизируем существующие foreach (AttributeDefinition attdef in attdefs.Where(n => dtags .Join(dtags2, a => a, b => b, (a, b) => a).Contains(n.Tag))) { AttributeDefinition ad = attdefs2.First(n => n.Tag == attdef.Tag); ad.Position = attdef.Position; #if ACAD2009 ad.TextStyle = attdef.TextStyle; #else ad.TextStyleId = attdef.TextStyleId; #endif //Если требуется - устанавливаем для атрибута значение по умолчанию if (setAttDefValues) { ad.TextString = attdef.TextString; } ad.Tag = attdef.Tag; ad.Prompt = attdef.Prompt; ad.LayerId = attdef.LayerId; ad.Rotation = attdef.Rotation; ad.LinetypeId = attdef.LinetypeId; ad.LineWeight = attdef.LineWeight; ad.LinetypeScale = attdef.LinetypeScale; ad.Annotative = attdef.Annotative; ad.Color = attdef.Color; ad.Height = attdef.Height; ad.HorizontalMode = attdef.HorizontalMode; ad.Invisible = attdef.Invisible; ad.IsMirroredInX = attdef.IsMirroredInX; ad.IsMirroredInY = attdef.IsMirroredInY; ad.Justify = attdef.Justify; ad.LockPositionInBlock = attdef.LockPositionInBlock; ad.MaterialId = attdef.MaterialId; ad.Oblique = attdef.Oblique; ad.Thickness = attdef.Thickness; ad.Transparency = attdef.Transparency; ad.VerticalMode = attdef.VerticalMode; ad.Visible = attdef.Visible; ad.WidthFactor = attdef.WidthFactor; ad.CastShadows = attdef.CastShadows; ad.Constant = attdef.Constant; ad.FieldLength = attdef.FieldLength; ad.ForceAnnoAllVisible = attdef.ForceAnnoAllVisible; ad.Preset = attdef.Preset; ad.Prompt = attdef.Prompt; ad.Verifiable = attdef.Verifiable; ad.AdjustAlignment(db); } //3. Добавляем недостающие foreach (AttributeDefinition attdef in attdefs.Where(n => !dtags2.Contains(n.Tag))) { AttributeDefinition ad = new AttributeDefinition(); ad.SetDatabaseDefaults(); ad.Position = attdef.Position; #if ACAD2009 ad.TextStyle = attdef.TextStyle; #else ad.TextStyleId = attdef.TextStyleId; #endif ad.TextString = attdef.TextString; ad.Tag = attdef.Tag; ad.Prompt = attdef.Prompt; ad.LayerId = attdef.LayerId; ad.Rotation = attdef.Rotation; ad.LinetypeId = attdef.LinetypeId; ad.LineWeight = attdef.LineWeight; ad.LinetypeScale = attdef.LinetypeScale; ad.Annotative = attdef.Annotative; ad.Color = attdef.Color; ad.Height = attdef.Height; ad.HorizontalMode = attdef.HorizontalMode; ad.Invisible = attdef.Invisible; ad.IsMirroredInX = attdef.IsMirroredInX; ad.IsMirroredInY = attdef.IsMirroredInY; ad.Justify = attdef.Justify; ad.LockPositionInBlock = attdef.LockPositionInBlock; ad.MaterialId = attdef.MaterialId; ad.Oblique = attdef.Oblique; ad.Thickness = attdef.Thickness; ad.Transparency = attdef.Transparency; ad.VerticalMode = attdef.VerticalMode; ad.Visible = attdef.Visible; ad.WidthFactor = attdef.WidthFactor; ad.CastShadows = attdef.CastShadows; ad.Constant = attdef.Constant; ad.FieldLength = attdef.FieldLength; ad.ForceAnnoAllVisible = attdef.ForceAnnoAllVisible; ad.Preset = attdef.Preset; ad.Prompt = attdef.Prompt; ad.Verifiable = attdef.Verifiable; _btr.AppendEntity(ad); t.AddNewlyCreatedDBObject(ad, true); ad.AdjustAlignment(db); } //Синхронизируем все вхождения данного анонимного определения блока _btr.AttSync(directOnly, removeSuperfluous, setAttDefValues); } //Обновляем геометрию определений анонимных блоков, полученных на основе //этого динамического блока btr.UpdateAnonymousBlocks(); t.Commit(); } } // } }
public static ObjectId AppendBlockItem(Point3d insertPointWcs, ObjectId blockTableRecordId, Dictionary <string, string> attrTextValues) { 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(insertPointWcs, blockTableRecordId); br.SetDatabaseDefaults(); 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); foreach (AttributeDefinition acAtt in attributes) { acAtt.UpgradeOpen(); acAtt.AdjustAlignment(br.Database); // acAtt.RecordGraphicsModified(true); // if (!acAtt.Constant) { using (AttributeReference acAttRef = new AttributeReference()) { acAttRef.SetAttributeFromBlock(acAtt, br.BlockTransform); if (attrTextValues != null) { if (attrTextValues.ContainsKey(acAtt.Tag)) { acAttRef.TextString = attrTextValues[acAtt.Tag]; } else { acAttRef.TextString = acAtt.TextString; } } else { acAttRef.TextString = acAtt.TextString; } acAttRef.AdjustAlignment(br.Database); // acAttRef.RecordGraphicsModified(true); // br.AttributeCollection.AppendAttribute(acAttRef); trans.AddNewlyCreatedDBObject(acAttRef, true); } } } br.RecordGraphicsModified(true); }); return(resBlockId); }
/// <summary> /// Creates BlockReference from the block with the given name. /// Throws ArgumentException if block with such a name does not exist. /// </summary> /// <param name="blockName"></param> /// <param name="insertionPoint"></param> /// <param name="space">The model space or some of the paper spaces</param> /// <param name="blockTable">The block table of the associated drawing in the helper.</param> /// <returns>The BlockReference of the block</returns> private BlockReference CreateBlockReference(string blockName, UnitsValue sourceBlockMeasurementUnits, Point3d insertionPoint, BlockTableRecord space, BlockTable blockTable) { Matrix3d ucs = _ed.CurrentUserCoordinateSystem; BlockReference newBlockReference; //All open objects opened during a transaction are closed at the end of the transaction. using (Transaction transaction = _db.TransactionManager.StartTransaction()) { blockTable.UpgradeOpen(); // If the DWG already contains this block definition we will create a block reference and not a copy of the same definition if (!blockTable.Has(blockName)) { _logger.Error(MethodBase.GetCurrentMethod().DeclaringType.FullName + "." + MethodBase.GetCurrentMethod().Name + " : Block with name '" + blockName + "' does not exist."); transaction.Abort(); throw new ArgumentException("Block with name '" + blockName + "' does not exist."); } BlockTableRecord sourceBlockTableRecord = (BlockTableRecord)transaction.GetObject(blockTable[blockName], OpenMode.ForRead); newBlockReference = new BlockReference(insertionPoint, sourceBlockTableRecord.ObjectId); var converter = new MeasurementUnitsConverter(); var scaleFactor = converter.GetScaleRatio(sourceBlockMeasurementUnits, blockTable.Database.Insunits); _ed.CurrentUserCoordinateSystem = Matrix3d.Identity; newBlockReference.TransformBy(ucs); _ed.CurrentUserCoordinateSystem = ucs; newBlockReference.ScaleFactors = new Scale3d(scaleFactor); space.UpgradeOpen(); space.AppendEntity(newBlockReference); transaction.AddNewlyCreatedDBObject(newBlockReference, true); AttributeCollection atcoll = newBlockReference.AttributeCollection; foreach (ObjectId subid in sourceBlockTableRecord) { var entity = (Entity)subid.GetObject(OpenMode.ForRead); var attributeDefinition = entity as AttributeDefinition; if (attributeDefinition != null) { var attributeReference = new AttributeReference(); attributeReference.SetPropertiesFrom(attributeDefinition); attributeReference.Visible = attributeDefinition.Visible; attributeReference.SetAttributeFromBlock(attributeDefinition, newBlockReference.BlockTransform); attributeReference.HorizontalMode = attributeDefinition.HorizontalMode; attributeReference.VerticalMode = attributeDefinition.VerticalMode; attributeReference.Rotation = attributeDefinition.Rotation; attributeReference.Position = attributeDefinition.Position + insertionPoint.GetAsVector(); attributeReference.Tag = attributeDefinition.Tag; attributeReference.FieldLength = attributeDefinition.FieldLength; attributeReference.TextString = attributeDefinition.TextString; attributeReference.AdjustAlignment(_db); atcoll.AppendAttribute(attributeReference); transaction.AddNewlyCreatedDBObject(attributeReference, true); } } transaction.Commit(); } _ed.Regen(); return(newBlockReference); }
public ObjectId ImportDynamicBlockAndFillItsProperties(string dynamicBlockPath, Point3d basePoint, Hashtable dynamicBlockProperties, Hashtable dynamicBlockAttributes) { var resultingObjectId = new ObjectId(); var blockname = dynamicBlockPath.Remove(0, dynamicBlockPath.LastIndexOf("\\", StringComparison.Ordinal) + 1); blockname = blockname.Remove(blockname.LastIndexOf(".dwg", StringComparison.Ordinal)); using (_doc.LockDocument()) { using (var inMemoryDb = new Database(false, true)) { inMemoryDb.ReadDwgFile(dynamicBlockPath, System.IO.FileShare.Read, true, ""); using (var transaction = _doc.TransactionManager.StartTransaction()) { var blockTable = (BlockTable)transaction.GetObject(_db.BlockTableId, OpenMode.ForRead); AttributeCollection atcoll; if (blockTable.Has(blockname)) { var currentSpace = (BlockTableRecord)_db.CurrentSpaceId.GetObject(OpenMode.ForWrite); var newDynamicBlockDefinition = (BlockTableRecord)transaction.GetObject(blockTable[blockname], OpenMode.ForRead); // Create a block reference to the existing block definition var newBlockReference = new BlockReference(basePoint, newDynamicBlockDefinition.ObjectId); newBlockReference.TransformBy(Matrix3d.Identity); newBlockReference.ScaleFactors = new Scale3d(1, 1, 1); currentSpace.AppendEntity(newBlockReference); transaction.AddNewlyCreatedDBObject(newBlockReference, true); resultingObjectId = newBlockReference.ObjectId; using (var pc = newBlockReference.DynamicBlockReferencePropertyCollection) { foreach (DynamicBlockReferenceProperty prop in pc) { if (dynamicBlockProperties.ContainsKey(prop.PropertyName)) { prop.Value = dynamicBlockProperties[prop.PropertyName]; } } } var bref3 = (BlockReference)transaction.GetObject(newBlockReference.ObjectId, OpenMode.ForWrite); atcoll = bref3.AttributeCollection; foreach (var subid in newDynamicBlockDefinition) { var ent = (Entity)subid.GetObject(OpenMode.ForRead); var attDef = ent as AttributeDefinition; if (attDef == null) { continue; } var attRef = new AttributeReference(); attRef.SetPropertiesFrom(attDef); attRef.SetAttributeFromBlock(attDef, newBlockReference.BlockTransform); attRef.AdjustAlignment(_db); attRef.TextString = dynamicBlockAttributes.ContainsKey(attRef.Tag) ? dynamicBlockAttributes[attRef.Tag].ToString() : attDef.TextString; atcoll.AppendAttribute(attRef); transaction.AddNewlyCreatedDBObject(attRef, true); } transaction.Commit(); _ed.Regen(); return(resultingObjectId); } // There is not such block definition, so we are inserting/creating new one var sourceBlockId = _db.Insert(blockname, inMemoryDb, false); // We continue the creation of the new block definition of the sourceDWG var btrec = (BlockTableRecord)sourceBlockId.GetObject(OpenMode.ForRead); btrec.UpgradeOpen(); btrec.Name = blockname; btrec.DowngradeOpen(); var currentSpaceBlockTableRecord = (BlockTableRecord)_db.CurrentSpaceId.GetObject(OpenMode.ForWrite); // We have created the block definition up there, and now we create the block reference to this block definition var bref = new BlockReference(basePoint, sourceBlockId); currentSpaceBlockTableRecord.AppendEntity(bref); transaction.AddNewlyCreatedDBObject(bref, true); if (bref.IsDynamicBlock) { resultingObjectId = bref.ObjectId; using (var pc = bref.DynamicBlockReferencePropertyCollection) { try { foreach (DynamicBlockReferenceProperty prop in pc) { if (dynamicBlockProperties.ContainsKey(prop.PropertyName)) { prop.Value = dynamicBlockProperties[prop.PropertyName]; } } } catch (Exception exception) { _logger.Error("Error applying dynamic block properties.", exception); throw; } } } // Copy the attributes var btAttRec = (BlockTableRecord)bref.BlockTableRecord.GetObject(OpenMode.ForWrite); var bref2 = (BlockReference)transaction.GetObject(bref.ObjectId, OpenMode.ForWrite); atcoll = bref2.AttributeCollection; foreach (var subid in btAttRec) { var ent = (Entity)subid.GetObject(OpenMode.ForRead); var attDef = ent as AttributeDefinition; if (attDef == null) { continue; } var attRef = new AttributeReference(); attRef.SetPropertiesFrom(attDef); attRef.SetAttributeFromBlock(attDef, bref.BlockTransform); attRef.AdjustAlignment(_db); attRef.TextString = dynamicBlockAttributes.ContainsKey(attRef.Tag) ? dynamicBlockAttributes[attRef.Tag].ToString() : attDef.TextString; atcoll.AppendAttribute(attRef); transaction.AddNewlyCreatedDBObject(attRef, true); } transaction.Commit(); } _ed.Regen(); } } return(resultingObjectId); }
public ObjectId InsertBlockReference(Database db, string layerName, string blockName, Point3d position, double rotation, Scale3d scale, Dictionary <string, string> attNamevalues) { using (var trans = db.TransactionManager.StartTransaction()) { var blkTbl = trans.GetObject(db.BlockTableId, OpenMode.ForRead) as BlockTable; if (!blkTbl.Has(blockName)) { return(ObjectId.Null); } var oId = blkTbl[blockName]; var spaceRec = trans.GetObject(db.CurrentSpaceId, OpenMode.ForRead) as BlockTableRecord; var blkTblRec = trans.GetObject(oId, OpenMode.ForRead) as BlockTableRecord; BlockReference br = new BlockReference(position, oId); br.ScaleFactors = scale; br.Rotation = rotation; br.Layer = layerName; spaceRec.UpgradeOpen(); ObjectId brId = spaceRec.AppendEntity(br); trans.AddNewlyCreatedDBObject(br, true); spaceRec.DowngradeOpen(); if (blkTblRec.HasAttributeDefinitions) { foreach (ObjectId id in blkTblRec) { var attr = trans.GetObject(id, OpenMode.ForRead) as AttributeDefinition; if (attr != null) { AttributeReference attrRef = new AttributeReference(); attrRef.SetAttributeFromBlock(attr, br.BlockTransform); attrRef.Position = attr.Position.TransformBy(br.BlockTransform); attrRef.Rotation = attr.Rotation; attrRef.AdjustAlignment(db); if (attNamevalues.ContainsKey(attr.Tag.ToString())) { attrRef.TextString = attNamevalues[attr.Tag.ToUpper()]; } br.AttributeCollection.AppendAttribute(attrRef); trans.AddNewlyCreatedDBObject(attrRef, true); } } } trans.Commit(); return(brId); } }
public void MakeCoordGrid() { if (!CheckLicense.Check()) { return; } Autodesk.AutoCAD.ApplicationServices.Document doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument; Autodesk.AutoCAD.DatabaseServices.Database db = doc.Database; ObjectId textStyleId = ObjectId.Null; using (Transaction tr = db.TransactionManager.StartTransaction()) using (TextStyleTable tt = (TextStyleTable)tr.GetObject(db.TextStyleTableId, OpenMode.ForRead)) { if (tt.Has(TextStyleName)) { textStyleId = tt[TextStyleName]; } tr.Commit(); } ObjectId textLayerId = AcadUtility.AcadEntity.GetOrCreateLayer(db, TextLayerName, Color.FromColorIndex(ColorMethod.ByAci, 1)); ObjectId lineLayerId = AcadUtility.AcadEntity.GetOrCreateLayer(db, LineLayerName, Color.FromColorIndex(ColorMethod.ByAci, 3)); ObjectId blockId = GetOrCreateBlock(db, BlockName, textLayerId, lineLayerId, textStyleId); Matrix3d ucs2wcs = AcadUtility.AcadGraphics.UcsToWcs; Matrix3d wcs2ucs = AcadUtility.AcadGraphics.WcsToUcs; // Pick polyline PromptPointResult ptRes = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.Editor.GetPoint("\nKöşe noktası: "); if (PolylineJig.Jig(ptRes.Value, out Point3dCollection points)) { int xmin = int.MaxValue; int xmax = int.MinValue; int ymin = int.MaxValue; int ymax = int.MinValue; for (int i = 0; i < 4; i++) { Point3d pt = points[i]; xmin = Math.Min(xmin, (int)pt.X); xmax = Math.Max(xmax, (int)pt.X); ymin = Math.Min(ymin, (int)pt.Y); ymax = Math.Max(ymax, (int)pt.Y); } // Interval PromptIntegerOptions intOpts = new PromptIntegerOptions("\nAralık: "); intOpts.AllowNegative = false; intOpts.AllowZero = false; intOpts.AllowNone = false; intOpts.DefaultValue = Properties.Settings.Default.Command_COORDGRID_Interval; intOpts.UseDefaultValue = true; PromptIntegerResult intRes = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.Editor.GetInteger(intOpts); if (intRes.Status == PromptStatus.OK) { Interval = intRes.Value; } else { return; } // Round limits to multiples of the interval xmin = (int)Math.Floor((double)xmin / Interval) * Interval; xmax = (int)Math.Ceiling((double)xmax / Interval) * Interval; ymin = (int)Math.Floor((double)ymin / Interval) * Interval; ymax = (int)Math.Ceiling((double)ymax / Interval) * Interval; // Text height PromptDoubleOptions thOpts = new PromptDoubleOptions("\nYazı yüksekliği: "); thOpts.AllowNegative = false; thOpts.AllowZero = false; thOpts.AllowNone = false; thOpts.DefaultValue = Properties.Settings.Default.Command_COORDGRID_TextHeight; thOpts.UseDefaultValue = true; PromptDoubleResult thRes = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.Editor.GetDouble(thOpts); if (thRes.Status == PromptStatus.OK) { TextHeight = thRes.Value; } else { return; } // Save settings Properties.Settings.Default.Command_COORDGRID_TextHeight = TextHeight; Properties.Settings.Default.Command_COORDGRID_Interval = Interval; Properties.Settings.Default.Save(); // Print grid NumberFormatInfo nfi = (NumberFormatInfo)CultureInfo.InvariantCulture.NumberFormat.Clone(); nfi.NumberGroupSeparator = " "; nfi.NumberDecimalDigits = 0; using (Transaction tr = db.TransactionManager.StartTransaction()) using (BlockTable bt = (BlockTable)tr.GetObject(db.BlockTableId, OpenMode.ForRead)) using (BlockTableRecord btr = (BlockTableRecord)tr.GetObject(db.CurrentSpaceId, OpenMode.ForWrite)) { BlockTableRecord blockDef = (BlockTableRecord)tr.GetObject(blockId, OpenMode.ForRead); for (int x = xmin; x <= xmax; x += Interval) { for (int y = ymin; y <= ymax; y += Interval) { Point3d v = new Point3d(x, y, 0); if (!PolylineContains(points, v)) { continue; } BlockReference blockRef = AcadUtility.AcadEntity.CreateBlockReference(db, blockId, v, TextHeight, 0); btr.AppendEntity(blockRef); tr.AddNewlyCreatedDBObject(blockRef, true); // Set attributes foreach (ObjectId id in blockDef) { AttributeDefinition attDef = tr.GetObject(id, OpenMode.ForRead) as AttributeDefinition; if (attDef != null) { using (AttributeReference attRef = new AttributeReference()) { attRef.SetDatabaseDefaults(db); attRef.SetAttributeFromBlock(attDef, blockRef.BlockTransform); blockRef.AttributeCollection.AppendAttribute(attRef); tr.AddNewlyCreatedDBObject(attRef, true); attRef.TextString = attDef.Tag == "X" ? x.ToString("n", nfi) : y.ToString("n", nfi); attRef.AdjustAlignment(db); } } } } } tr.Commit(); } } }
/// <summary> /// /// * Insert Drawing As Block - DWG or DXF * /// the source drawig should be drawn as number of /// separate entites with or without attributes /// /// </summary> /// <param name="destinationDocument"></param> /// <param name="sourceDrawing"></param> /// <param name="insertionPoint"></param> /// <param name="transforMatrix"> </param> /// <exception cref="NotImplementedException">Not implemented for DXFs</exception> /// <returns>ObjectID of the Block Def that was imported.</returns> private void ReplaceBlockRefWithDWG(Document destinationDocument, string sourceDrawing, Point3d insertionPoint, Matrix3d transforMatrix) { Point3d oldPoint = insertionPoint.TransformBy(transforMatrix.Inverse()); insertionPoint = new Point3d(0, 0, 0); Database destinationDb = destinationDocument.Database; Editor ed = destinationDocument.Editor; string blockname = sourceDrawing.Remove(0, sourceDrawing.LastIndexOf("\\", StringComparison.Ordinal) + 1); blockname = blockname.Substring(0, blockname.Length - 4); // remove the extension using (destinationDocument.LockDocument()) { using (var inMemoryDb = new Database(false, true)) { if (sourceDrawing.LastIndexOf(".dwg", StringComparison.Ordinal) > 0) { inMemoryDb.ReadDwgFile(sourceDrawing, FileShare.ReadWrite, true, ""); } else if (sourceDrawing.LastIndexOf(".dxf", StringComparison.Ordinal) > 0) { throw new NotImplementedException("DXFs not suppported"); //inMemoryDb.DxfIn(string filename, string logFilename); } using (var transaction = destinationDocument.TransactionManager.StartTransaction()) { var destinationDatabaseBlockTable = (BlockTable) transaction.GetObject(destinationDb.BlockTableId, OpenMode.ForRead); ObjectId sourceBlockObjectId; if (destinationDatabaseBlockTable.Has(blockname)) { ed.WriteMessage("Block " + blockname + " already exists.\n Attempting to create block reference..."); var destinationDatabaseCurrentSpace = (BlockTableRecord) destinationDb.CurrentSpaceId.GetObject(OpenMode.ForWrite); var destinationDatabaseBlockDefinition = (BlockTableRecord) transaction.GetObject(destinationDatabaseBlockTable[blockname], OpenMode.ForRead); sourceBlockObjectId = destinationDatabaseBlockDefinition.ObjectId; // Create a block reference to the existing block definition using (var blockReference = new BlockReference(insertionPoint, sourceBlockObjectId)) { //Matrix3d Mat = Matrix3d.Identity; Vector3d mov = new Vector3d(oldPoint.X, oldPoint.Y, oldPoint.Z); mov = mov.TransformBy(transforMatrix); blockReference.TransformBy(transforMatrix); blockReference.TransformBy(Matrix3d.Displacement(mov)); blockReference.ScaleFactors = new Scale3d(1, 1, 1); destinationDatabaseCurrentSpace.AppendEntity(blockReference); transaction.AddNewlyCreatedDBObject(blockReference, true); ed.Regen(); transaction.Commit(); // At this point the Bref has become a DBObject and can be disposed } return; } // There is not such block definition, so we are inserting/creating new one sourceBlockObjectId = destinationDb.Insert(blockname, inMemoryDb, true); #region Create Block Ref from the already imported Block Def // We continue here the creation of the new block reference of the already imported block definition var sourceDatabaseCurrentSpace = (BlockTableRecord) destinationDb.CurrentSpaceId.GetObject(OpenMode.ForWrite); using (var blockReference = new BlockReference(insertionPoint, sourceBlockObjectId)) { blockReference.ScaleFactors = new Scale3d(1, 1, 1); sourceDatabaseCurrentSpace.AppendEntity(blockReference); transaction.AddNewlyCreatedDBObject(blockReference, true); var blockTableRecord = (BlockTableRecord) blockReference.BlockTableRecord.GetObject(OpenMode.ForRead); var atcoll = blockReference.AttributeCollection; foreach (ObjectId subid in blockTableRecord) { var entity = (Entity) subid.GetObject(OpenMode.ForRead); var attributeDefinition = entity as AttributeDefinition; if (attributeDefinition == null) { continue; } var attributeReference = new AttributeReference(); attributeReference.SetPropertiesFrom(attributeDefinition); attributeReference.Visible = attributeDefinition.Visible; attributeReference.SetAttributeFromBlock(attributeDefinition, blockReference.BlockTransform); attributeReference.HorizontalMode = attributeDefinition.HorizontalMode; attributeReference.VerticalMode = attributeDefinition.VerticalMode; attributeReference.Rotation = attributeDefinition.Rotation; attributeReference.Position = attributeDefinition.Position + insertionPoint.GetAsVector(); attributeReference.Tag = attributeDefinition.Tag; attributeReference.FieldLength = attributeDefinition.FieldLength; attributeReference.TextString = attributeDefinition.TextString; attributeReference.AdjustAlignment(destinationDb); atcoll.AppendAttribute(attributeReference); transaction.AddNewlyCreatedDBObject(attributeReference, true); } var mov = new Vector3d(oldPoint.X, oldPoint.Y, oldPoint.Z); mov = mov.TransformBy(transforMatrix); blockReference.TransformBy(transforMatrix); blockReference.TransformBy(Matrix3d.Displacement(mov)); transaction.Commit(); } #endregion ed.Regen(); } } } }
addBlockRef(string strName, Point3d pnt3dIns, double dblRotation, List <string> attValues) { Database db = BaseObjs._db; Editor ed = BaseObjs._editor; BlockTableRecord btrx = null; BlockReference br = null; try { using (Transaction tr = BaseObjs.startTransactionDb()) { BlockTable bt = (BlockTable)db.BlockTableId.GetObject(OpenMode.ForRead); if (!bt.Has(strName)) { btrx = addBtr(strName); } else { btrx = (BlockTableRecord)bt[strName].GetObject(OpenMode.ForRead); } //---> debug only foreach (ObjectId idObj in btrx) { Entity ent = (Entity)idObj.GetObject(OpenMode.ForRead); AttributeDefinition ad = ent as AttributeDefinition; if (ad != null) { ed.WriteMessage(string.Format("\n{0}", ad.Tag)); } }//<--- debug only //BlockTableRecord Btr = (BlockTableRecord)DB.CurrentSpaceId.GetObject(OpenMode.ForWrite); btrx.UpgradeOpen(); using (btrx) { br = new BlockReference(pnt3dIns, btrx.ObjectId); using (br) { Matrix3d ucsMatrix = ed.CurrentUserCoordinateSystem; CoordinateSystem3d ucs = ucsMatrix.CoordinateSystem3d; Matrix3d mat3d = new Matrix3d(); mat3d = Matrix3d.Rotation(dblRotation, ucs.Zaxis, pnt3dIns); br.TransformBy(mat3d); br.ScaleFactors = new Scale3d(1, 1, 1); btrx.AppendEntity(br); tr.AddNewlyCreatedDBObject(br, true); BlockTableRecord btratt = (BlockTableRecord)br.BlockTableRecord.GetObject(OpenMode.ForRead); using (btratt) { Autodesk.AutoCAD.DatabaseServices.AttributeCollection ATTcol = br.AttributeCollection; foreach (ObjectId subid in btratt) { Entity ent = (Entity)subid.GetObject(OpenMode.ForRead); AttributeDefinition ad = ent as AttributeDefinition; if (ad != null) { AttributeReference ar = new AttributeReference(); ar.SetPropertiesFrom(ad); ar.SetAttributeFromBlock(ad, br.BlockTransform); ar.Visible = ad.Visible; ar.HorizontalMode = ad.HorizontalMode; ar.VerticalMode = ad.VerticalMode; ar.Rotation = ad.Rotation; ar.TextStyleId = ad.TextStyleId; ar.Position = ad.Position + pnt3dIns.GetAsVector(); ar.Tag = ad.Tag; ar.FieldLength = ad.FieldLength; ar.AdjustAlignment(db); //if (ar.Tag == "TOPTXT") // ar.TextString = strTop; //if (ar.Tag == "MIDTXT") // ar.TextString = strMid; //if (ar.Tag == "BOTTXT") // ar.TextString = strBot; ar.Position = ad.Position.TransformBy(br.BlockTransform); ATTcol.AppendAttribute(ar); tr.AddNewlyCreatedDBObject(ar, true); } } } br.DowngradeOpen(); } btrx.DowngradeOpen(); } tr.Commit(); } } catch (System.Exception ex) { BaseObjs.writeDebug(ex.Message + " Blocks.cs: line: 194"); } return(br); }