private AttributeDefinition _convertToAttribute(DBText text) { AttributeDefinition ad = new AttributeDefinition(); ad.SetDatabaseDefaults(HostApplicationServices.WorkingDatabase); ad.TextString = text.TextString; ad.HorizontalMode = text.HorizontalMode; ad.VerticalMode = text.VerticalMode; ad.Height = text.Height; ad.Annotative = text.Annotative; ad.Constant = false; ad.Verifiable = true; ad.Rotation = text.Rotation; ad.Tag = "анкера_отклонение"; ad.Prompt = "Отклонение " + (ad.Rotation == 0d ? "по горизонтали" : "по вертикали"); ad.Position = text.Position; ad.AlignmentPoint = text.AlignmentPoint; ad.AdjustAlignment(HostApplicationServices.WorkingDatabase); return(ad); }
public static AttributeDefinition ConvertToAttribute(this DBText text, string tag, string prompt) { AttributeDefinition ad = new AttributeDefinition(); ad.SetDatabaseDefaults(HostApplicationServices.WorkingDatabase); ad.TextString = text.TextString; ad.HorizontalMode = text.HorizontalMode; ad.VerticalMode = text.VerticalMode; ad.Height = text.Height; ad.Annotative = text.Annotative; ad.Constant = false; ad.Verifiable = true; ad.Rotation = text.Rotation; ad.Tag = tag; ad.Prompt = prompt; ad.Position = text.Position; ad.AlignmentPoint = text.AlignmentPoint; ad.AdjustAlignment(HostApplicationServices.WorkingDatabase); return(ad); }
private void _transformBy(Matrix3d matrix, Transaction trans, bool commit) { for (int i = 0; i < _entities.Count; i++) { Entity ent = _entities[i]; if (ent.ObjectId != ObjectId.Null) { ent = (Entity)ent.Id.GetObject(OpenMode.ForWrite, false, true); } ent.TransformBy(matrix); if (ent is AttributeDefinition) { try { AttributeDefinition ad = (AttributeDefinition)ent; //_appenedAttriuteDef(ref ad); ad.AdjustAlignment(Tools.GetAcadDatabase()); } catch { } } } if (commit) { /*BlockTableRecord btr = null; * if (this.BlockTableRecordId != ObjectId.Null) * { * btr = (BlockTableRecord)this.BlockTableRecordId.GetObject(OpenMode.ForRead, false, true); * }*/ trans.Commit(); /*if (btr != null) * { * btr.UpdateAnonymousBlocks(); * }*/ } }
private IEnumerable <Entity> _createAttrute(Point3d alignmentPoint, string prefix, Matrix3d transform) { alignmentPoint = alignmentPoint.TransformBy(Matrix3d.Displacement(transform.CoordinateSystem3d.Yaxis.MultiplyBy(2.0d * 0.2))); AttributeDefinition ad = new AttributeDefinition(); ad.SetDatabaseDefaults(Tools.GetAcadDatabase()); ad.Verifiable = true; ad.Tag = "отклонение_" + prefix; ad.TextString = "12"; ad.Annotative = AnnotativeStates.False; ad.Height = 2.0d; ad.HorizontalMode = TextHorizontalMode.TextLeft; ad.VerticalMode = TextVerticalMode.TextBottom; ad.Position = Point3d.Origin; ad.TransformBy(transform); ad.Position = alignmentPoint; ad.AlignmentPoint = alignmentPoint; ad.AdjustAlignment(Tools.GetAcadDatabase()); DBText adPrefix = new DBText(); adPrefix.SetDatabaseDefaults(Tools.GetAcadDatabase()); adPrefix.TextString = prefix; adPrefix.Height = 2.0d; adPrefix.Annotative = AnnotativeStates.False; adPrefix.HorizontalMode = TextHorizontalMode.TextRight; adPrefix.VerticalMode = TextVerticalMode.TextBottom; adPrefix.Position = Point3d.Origin; adPrefix.TransformBy(transform); adPrefix.AlignmentPoint = alignmentPoint; adPrefix.AdjustAlignment(Tools.GetAcadDatabase()); Rectangle3d?rectg = adPrefix.GetTextBoxCorners(); Polyline bound = new Polyline(5); bound.AddVertexAt(0, rectg.Value.LowerLeft.Add((rectg.Value.UpperLeft - rectg.Value.LowerLeft).Normalize().Negate().MultiplyBy(adPrefix.Height * 0.1))); bound.AddVertexAt(1, rectg.Value.UpperLeft.Add((rectg.Value.UpperLeft - rectg.Value.LowerLeft).Normalize().MultiplyBy(adPrefix.Height * 0.1))); bound.AddVertexAt(2, rectg.Value.UpperRight.Add((rectg.Value.UpperRight - rectg.Value.LowerRight).Normalize().MultiplyBy(adPrefix.Height * 0.1))); bound.AddVertexAt(3, rectg.Value.LowerRight.Add((rectg.Value.UpperRight - rectg.Value.LowerRight).Normalize().Negate().MultiplyBy(adPrefix.Height * 0.1))); bound.AddVertexAt(4, rectg.Value.LowerLeft.Add((rectg.Value.UpperLeft - rectg.Value.LowerLeft).Normalize().Negate().MultiplyBy(adPrefix.Height * 0.1))); Vector3d vector = rectg.Value.LowerRight - rectg.Value.LowerLeft; if (!transform.CoordinateSystem3d.Xaxis.IsCodirectionalTo(vector)) { Plane plane = new Plane(alignmentPoint, transform.CoordinateSystem3d.Yaxis, transform.CoordinateSystem3d.Zaxis); Matrix3d mat = Matrix3d.Mirroring(plane); ad.TransformBy(mat); ad.AdjustAlignment(Tools.GetAcadDatabase()); adPrefix.TransformBy(mat); adPrefix.AdjustAlignment(Tools.GetAcadDatabase()); bound.TransformBy(mat); } yield return(ad); yield return(adPrefix); yield return(bound); }
/// <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 AttributeDefinition CreateAttribute(Database db, Point3d pt, string tag, string prompt, string text, double textHeight, double rotation, double widthFactor, TextHorizontalMode horizontalMode, TextVerticalMode verticalMode, ObjectId textStyleId, ObjectId layerId) { using (CurrentDB curr = new CurrentDB(db)) { AttributeDefinition attdef = new AttributeDefinition(); attdef.SetDatabaseDefaults(db); attdef.Tag = tag; attdef.Prompt = prompt; attdef.TextString = text; attdef.Position = pt; attdef.Height = textHeight; attdef.Rotation = rotation; attdef.WidthFactor = widthFactor; if (horizontalMode == TextHorizontalMode.TextLeft) { if (verticalMode == TextVerticalMode.TextTop) { attdef.Justify = AttachmentPoint.TopLeft; } else if (verticalMode == TextVerticalMode.TextBase) { attdef.Justify = AttachmentPoint.BaseLeft; } else if (verticalMode == TextVerticalMode.TextBottom) { attdef.Justify = AttachmentPoint.BottomLeft; } else { attdef.Justify = AttachmentPoint.MiddleLeft; } } else if (horizontalMode == TextHorizontalMode.TextRight) { if (verticalMode == TextVerticalMode.TextTop) { attdef.Justify = AttachmentPoint.TopRight; } else if (verticalMode == TextVerticalMode.TextBase) { attdef.Justify = AttachmentPoint.BaseRight; } else if (verticalMode == TextVerticalMode.TextBottom) { attdef.Justify = AttachmentPoint.BottomRight; } else { attdef.Justify = AttachmentPoint.MiddleRight; } } else if (horizontalMode == TextHorizontalMode.TextMid || horizontalMode == TextHorizontalMode.TextCenter) { if (verticalMode == TextVerticalMode.TextTop) { attdef.Justify = AttachmentPoint.TopCenter; } else if (verticalMode == TextVerticalMode.TextBase) { attdef.Justify = AttachmentPoint.BaseCenter; } else if (verticalMode == TextVerticalMode.TextBottom) { attdef.Justify = AttachmentPoint.BottomCenter; } else { attdef.Justify = AttachmentPoint.MiddleCenter; } } else if (horizontalMode == TextHorizontalMode.TextAlign) { if (verticalMode == TextVerticalMode.TextTop) { attdef.Justify = AttachmentPoint.TopAlign; } else if (verticalMode == TextVerticalMode.TextBase) { attdef.Justify = AttachmentPoint.BaseAlign; } else if (verticalMode == TextVerticalMode.TextBottom) { attdef.Justify = AttachmentPoint.BottomAlign; } else { attdef.Justify = AttachmentPoint.MiddleAlign; } } else if (horizontalMode == TextHorizontalMode.TextFit) { if (verticalMode == TextVerticalMode.TextTop) { attdef.Justify = AttachmentPoint.TopFit; } else if (verticalMode == TextVerticalMode.TextBase) { attdef.Justify = AttachmentPoint.BaseFit; } else if (verticalMode == TextVerticalMode.TextBottom) { attdef.Justify = AttachmentPoint.BottomFit; } else { attdef.Justify = AttachmentPoint.MiddleFit; } } if (horizontalMode != TextHorizontalMode.TextLeft || verticalMode != TextVerticalMode.TextBase) { attdef.AlignmentPoint = pt; attdef.AdjustAlignment(db); } if (!textStyleId.IsNull) { attdef.TextStyleId = textStyleId; } if (!layerId.IsNull) { attdef.LayerId = layerId; } return(attdef); } }