Произвольное изменение точи расположения текста Multileader

Автор Тема: Произвольное изменение точи расположения текста Multileader  (Прочитано 9734 раз)

0 Пользователей и 1 Гость просматривают эту тему.

Оффлайн Алексей Кулик

  • Administrator
  • *****
  • Сообщений: 1096
  • Карма: 172
У меня как-то был один юзер, который работал на основании собственного шаблона, который со стандартным не плясал вообще никак. Во я там поразвлекался, разбираясь в настройках! :)
Все, что сказано - личное мнение.

Правила форума существуют не просто так!

Приводя в сообщении код, не забывайте про его форматирование!

Оффлайн AtomohodАвтор темы

  • ADN OPEN
  • ****
  • Сообщений: 453
  • Карма: 1
Причину я так и не нашел, написал альтернативу с применением кода от Kean Walmsley, использующего Jig. Но есть одна странность - хотя настройки должны быть получены из стиля мультилидера, высота при создании устанавливаается в 0 и никак не могу прописать чтобы она устанавливалась в коде сразу. Кто-нибудь может подсказать как это сделать?
Код - C# [Выбрать]
  1. [CommandMethod("00MTextToMleader")]
  2.         public static void MTextToLeader()
  3.         {
  4.             Queue < Entity > entities = SelectionUtilities.SelectObjectsOnScreen2Queue();
  5.             (ObjectId, Point3d, string, double) itemsTuple = entities.Peek().TextPropertyExtractor();
  6.             DirectionalLeader(itemsTuple.Item3, itemsTuple.Item2, itemsTuple.Item4);
  7.         }
  8.  
  9.         public class DirectionalLeaderJig: EntityJig
  10.         {
  11.             private Point3d _start, _end;
  12.             private string _contents;
  13.             private int _index;
  14.             private int _lineIndex;
  15.             private bool _started;
  16.             private ObjectId mlStyleId;
  17.             private ObjectId mTextStyleId;
  18.             private double width;
  19.  
  20.             public DirectionalLeaderJig(string txt, Point3d start, MLeader ld, double width): base(ld)
  21.             {
  22.                 // Store info that's passed in, but don't init the MLeader
  23.                 _contents = txt;
  24.                 _start = start;
  25.                 _end = start;
  26.                 _started = false;
  27.                 mlStyleId = GetMleaderStyleObjectId();
  28.                 mTextStyleId = GetMTextStyleObjectId();
  29.                 this.width = width;
  30.             }
  31.  
  32.             // A fairly standard Sampler function
  33.  
  34.             protected override SamplerStatus Sampler(JigPrompts prompts)
  35.             {
  36.                 var po = new JigPromptPointOptions();
  37.                 po.UserInputControls = (UserInputControls.Accept3dCoordinates | UserInputControls.NoNegativeResponseAccepted);
  38.                 po.Message = "\nEnd point";
  39.                 var res = prompts.AcquirePoint(po);
  40.                 if ( _end == res.Value )
  41.                 {
  42.                     return SamplerStatus.NoChange;
  43.                 }
  44.                 else
  45.                     if ( res.Status == PromptStatus.OK )
  46.                     {
  47.                         _end = res.Value;
  48.                         return SamplerStatus.OK;
  49.                     }
  50.  
  51.                 return SamplerStatus.Cancel;
  52.             }
  53.  
  54.             protected override bool Update()
  55.             {
  56.                 var ml = (MLeader) Entity;
  57.                 if ( !_started )
  58.                 {
  59.                     if ( _start.DistanceTo(_end) > Tolerance.Global.EqualPoint )
  60.                     {
  61.                         // When the jig actually starts - and we have mouse movement -
  62.  
  63.                         // we create the MText and init the MLeader
  64.                         ml.ContentType = ContentType.MTextContent;
  65.                         ml.MLeaderStyle = mlStyleId;
  66.                         var mt = new MText();
  67.                         mt.TextStyleId = mTextStyleId;
  68.                         mt.Width = width;
  69.                         mt.Contents = _contents;
  70.                         ml.MText = mt;
  71.  
  72.                         // Create the MLeader cluster and add a line to it
  73.                         _index = ml.AddLeader();
  74.                         _lineIndex = ml.AddLeaderLine(_index);
  75.  
  76.                         // Set the vertices on the line
  77.                         ml.AddFirstVertex(_lineIndex, _start);
  78.                         ml.AddLastVertex(_lineIndex, _end);
  79.  
  80.                         // Make sure we don't do this again
  81.                         _started = true;
  82.                     }
  83.                 }
  84.                 else
  85.                 {
  86.                     // We only make the MLeader visible on the second time through
  87.  
  88.                     // (this also helps avoid some strange geometry flicker)
  89.                     ml.Visible = true;
  90.  
  91.                     // We already have a line, so just set its last vertex
  92.                     ml.SetLastVertex(_lineIndex, _end);
  93.                 }
  94.  
  95.                 if ( _started )
  96.                 {
  97.                     // Set the direction of the text to depend on the X of the end-point
  98.  
  99.                     // (i.e. is if to the left or right of the start-point?)
  100.                     var dl = new Vector3d((_end.X >= _start.X ? 1 : -1), 0, 0);
  101.                     ml.SetDogleg(_index, dl);
  102.                 }
  103.  
  104.                 return true;
  105.             }
  106.  
  107.             public static ObjectId GetMleaderStyleObjectId()
  108.             {
  109.                 var doc = Application.DocumentManager.MdiActiveDocument;
  110.                 var ed = doc.Editor;
  111.                 var db = doc.Database;
  112.                 var tr = db.TransactionManager.StartTransaction();
  113.                 ObjectId mlStyleId = default;
  114.                 using ( tr )
  115.                 {
  116.                     DBDictionary mlStyles = (DBDictionary) tr.GetObject(db.MLeaderStyleDictionaryId, OpenMode.ForRead);
  117.                     if ( mlStyles.Contains("Multileader") )
  118.                     {
  119.                         mlStyleId = mlStyles.GetAt("Multileader");
  120.                     }
  121.  
  122.                     tr.Commit();
  123.                 }
  124.  
  125.                 return mlStyleId;
  126.             }
  127.  
  128.             public static ObjectId GetMTextStyleObjectId()
  129.             {
  130.                 var doc = Application.DocumentManager.MdiActiveDocument;
  131.                 var ed = doc.Editor;
  132.                 var db = doc.Database;
  133.                 var tr = db.TransactionManager.StartTransaction();
  134.                 ObjectId mlStyleId = default;
  135.                 using ( tr )
  136.                 {
  137.                     TextStyleTable mlStyles = (TextStyleTable) tr.GetObject(db.TextStyleTableId, OpenMode.ForRead);
  138.                     if ( mlStyles.Has("Standard") )
  139.                     {
  140.                         mlStyleId = mlStyles[ "Standard" ];
  141.                     }
  142.  
  143.                     tr.Commit();
  144.                 }
  145.  
  146.                 return mlStyleId;
  147.             }
  148.         }
  149.  
  150.         public static void DirectionalLeader(string content, Point3d start, double width)
  151.         {
  152.             var doc = Application.DocumentManager.MdiActiveDocument;
  153.             var ed = doc.Editor;
  154.             var db = doc.Database;
  155.  
  156.             // Start a transaction, as we'll be jigging a db-resident object
  157.             using ( var tr = db.TransactionManager.StartTransaction() )
  158.             {
  159.                 var bt = (BlockTable) tr.GetObject(db.BlockTableId, OpenMode.ForRead, false);
  160.                 var btr = (BlockTableRecord) tr.GetObject(db.CurrentSpaceId, OpenMode.ForWrite, false);
  161.  
  162.                 // Create and pass in an invisible MLeader
  163.  
  164.                 // This helps avoid flickering when we start the jig
  165.                 var ml = new MLeader();
  166.                 ml.Visible = false;
  167.  
  168.                 // Create jig
  169.                 var jig = new DirectionalLeaderJig(content, start, ml, width);
  170.  
  171.                 // Add the MLeader to the drawing: this allows it to be displayed
  172.                 btr.AppendEntity(ml);
  173.                 tr.AddNewlyCreatedDBObject(ml, true);
  174.  
  175.                 // Set end point in the jig
  176.                 var res = ed.Drag(jig);
  177.  
  178.                 // If all is well, commit
  179.                 if ( res.Status == PromptStatus.OK )
  180.                 {
  181.                     tr.Commit();
  182.                 }
  183.             }
  184.         }

Оффлайн Александр Ривилис

  • Administrator
  • *****
  • Сообщений: 13829
  • Карма: 1784
  • Рыцарь ObjectARX
  • Skype: rivilis
Но есть одна странность - хотя настройки должны быть получены из стиля мультилидера, высота при создании устанавливаается в 0 и никак не могу прописать чтобы она устанавливалась в коде сразу
Ты про высоту MText или про высоту текста в MText или еще про какую-то высоту?
Высота текста в MText задаётся при помощи кода форматирования \Hn.n :
https://adndevblog.typepad.com/autocad/2017/09/dissecting-mtext-format-codes.html
Высота самого MText задаётся при помощи MText.Height
Не забывайте про правильное Форматирование кода на форуме
Создание и добавление Autodesk Screencast видео в сообщение на форуме
Если Вы задали вопрос и на форуме появился правильный ответ, то не забудьте про кнопку Решение

Оффлайн AtomohodАвтор темы

  • ADN OPEN
  • ****
  • Сообщений: 453
  • Карма: 1
Ты про высоту MText или про высоту текста в MText или еще про какую-то высоту?
Про высоту текста во вставленном мультилидере, она устанавливается в 0 несмотря на то, что в стиле текста на котором основан мультилидер стоит 600 мм.

Оффлайн Александр Ривилис

  • Administrator
  • *****
  • Сообщений: 13829
  • Карма: 1784
  • Рыцарь ObjectARX
  • Skype: rivilis
Atomohod,
Принудительно задай mt.TextHeight в значение, которое в текстовом стиле.
Не забывайте про правильное Форматирование кода на форуме
Создание и добавление Autodesk Screencast видео в сообщение на форуме
Если Вы задали вопрос и на форуме появился правильный ответ, то не забудьте про кнопку Решение

Оффлайн AtomohodАвтор темы

  • ADN OPEN
  • ****
  • Сообщений: 453
  • Карма: 1
Принудительно задай mt.TextHeight в значение, которое в текстовом стиле.
Попробовал, в явном виде - все равно 0 при вставке.

Оффлайн Александр Ривилис

  • Administrator
  • *****
  • Сообщений: 13829
  • Карма: 1784
  • Рыцарь ObjectARX
  • Skype: rivilis
Принудительно задай mt.TextHeight в значение, которое в текстовом стиле.
Попробовал, в явном виде - все равно 0 при вставке.
1. Где видео?
2. Где полный тестовый код (проект, на котором можно проверять)?
3. Нужна помощь или нет?
Не забывайте про правильное Форматирование кода на форуме
Создание и добавление Autodesk Screencast видео в сообщение на форуме
Если Вы задали вопрос и на форуме появился правильный ответ, то не забудьте про кнопку Решение

Отмечено как Решение Александр Ривилис 29-05-2019, 22:25:46

Оффлайн Александр Ривилис

  • Administrator
  • *****
  • Сообщений: 13829
  • Карма: 1784
  • Рыцарь ObjectARX
  • Skype: rivilis
Код - C# [Выбрать]
  1. // (C) Copyright 2019 by  
  2. //
  3. using System;
  4. using Autodesk.AutoCAD.Runtime;
  5. using Autodesk.AutoCAD.ApplicationServices;
  6. using Autodesk.AutoCAD.DatabaseServices;
  7. using Autodesk.AutoCAD.Geometry;
  8. using Autodesk.AutoCAD.EditorInput;
  9.  
  10. #pragma warning disable 0618
  11.  
  12. // This line is not mandatory, but improves loading performances
  13. [assembly: CommandClass(typeof(CreateMLeader.MyCommands))]
  14.  
  15. namespace CreateMLeader
  16. {
  17.  
  18.   // This class is instantiated by AutoCAD for each document when
  19.   // a command is called by the user the first time in the context
  20.   // of a given document. In other words, non static data in this class
  21.   // is implicitly per-document!
  22.   public class MyCommands
  23.   {
  24.     [CommandMethod("00MTextToMleader")]
  25.     public static void MTextToLeader()
  26.     {
  27.       // Queue<Entity> entities = SelectionUtilities.SelectObjectsOnScreen2Queue();
  28.       // (ObjectId, Point3d, string, double) itemsTuple = entities.Peek().TextPropertyExtractor();
  29.       Document doc = Application.DocumentManager.CurrentDocument;
  30.       if (doc == null) return;
  31.       Editor ed = doc.Editor;
  32.       PromptPointResult rsPnt = ed.GetPoint("\nGet start point");
  33.       if (rsPnt.Status != PromptStatus.OK)
  34.         return;
  35.       DirectionalLeader("ABCDEFGH", rsPnt.Value, 100.0);
  36.     }
  37.  
  38.     public class DirectionalLeaderJig : EntityJig
  39.     {
  40.       private Point3d _start, _end;
  41.       private string _contents;
  42.       private int _index;
  43.       private int _lineIndex;
  44.       private bool _started;
  45.       private ObjectId mlStyleId;
  46.       private ObjectId mTextStyleId;
  47.       private double width;
  48.  
  49.       public DirectionalLeaderJig(string txt, Point3d start, MLeader ld, double width) : base(ld)
  50.       {
  51.         // Store info that's passed in, but don't init the MLeader
  52.         _contents = txt;
  53.         _start = start;
  54.         _end = start;
  55.         _started = false;
  56.         mlStyleId = GetMleaderStyleObjectId();
  57.         mTextStyleId = GetMTextStyleObjectId();
  58.         this.width = width;
  59.       }
  60.  
  61.       // A fairly standard Sampler function
  62.  
  63.       protected override SamplerStatus Sampler(JigPrompts prompts)
  64.       {
  65.         var po = new JigPromptPointOptions();
  66.         po.UserInputControls = (UserInputControls.Accept3dCoordinates | UserInputControls.NoNegativeResponseAccepted);
  67.         po.Message = "\nEnd point";
  68.         var res = prompts.AcquirePoint(po);
  69.         if (_end == res.Value)
  70.         {
  71.           return SamplerStatus.NoChange;
  72.         }
  73.         else
  74.             if (res.Status == PromptStatus.OK)
  75.         {
  76.           _end = res.Value;
  77.           return SamplerStatus.OK;
  78.         }
  79.  
  80.         return SamplerStatus.Cancel;
  81.       }
  82.  
  83.       protected override bool Update()
  84.       {
  85.         var ml = (MLeader)Entity;
  86.         if (!_started)
  87.         {
  88.           if (_start.DistanceTo(_end) > Tolerance.Global.EqualPoint)
  89.           {
  90.             // When the jig actually starts - and we have mouse movement -
  91.  
  92.             // we create the MText and init the MLeader
  93.             ml.ContentType = ContentType.MTextContent;
  94.             ml.MLeaderStyle = mlStyleId;
  95.             var mt = new MText();
  96.             mt.SetDatabaseDefaults();
  97.             mt.TextStyleId = mTextStyleId;
  98.             mt.Width = width;
  99.             using (TextStyleTableRecord txtTblRec =
  100.               mTextStyleId.Open(OpenMode.ForRead) as TextStyleTableRecord)
  101.             {
  102.               mt.TextHeight = txtTblRec.TextSize;
  103.             }
  104.             mt.Contents = _contents;
  105.             ml.MText = mt;
  106.             // Create the MLeader cluster and add a line to it
  107.             _index = ml.AddLeader();
  108.             _lineIndex = ml.AddLeaderLine(_index);
  109.  
  110.             // Set the vertices on the line
  111.             ml.AddFirstVertex(_lineIndex, _start);
  112.             ml.AddLastVertex(_lineIndex, _end);
  113.  
  114.             // Make sure we don't do this again
  115.             _started = true;
  116.           }
  117.         }
  118.         else
  119.         {
  120.           // We only make the MLeader visible on the second time through
  121.  
  122.           // (this also helps avoid some strange geometry flicker)
  123.           ml.Visible = true;
  124.  
  125.           // We already have a line, so just set its last vertex
  126.           ml.SetLastVertex(_lineIndex, _end);
  127.         }
  128.  
  129.         if (_started)
  130.         {
  131.           // Set the direction of the text to depend on the X of the end-point
  132.  
  133.           // (i.e. is if to the left or right of the start-point?)
  134.           var dl = new Vector3d((_end.X >= _start.X ? 1 : -1), 0, 0);
  135.           ml.SetDogleg(_index, dl);
  136.         }
  137.  
  138.         return true;
  139.       }
  140.  
  141.       public static ObjectId GetMleaderStyleObjectId()
  142.       {
  143.         var doc = Application.DocumentManager.MdiActiveDocument;
  144.         var ed = doc.Editor;
  145.         var db = doc.Database;
  146.         var tr = db.TransactionManager.StartTransaction();
  147.         ObjectId mlStyleId = ObjectId.Null;
  148.         using (tr)
  149.         {
  150.           DBDictionary mlStyles = (DBDictionary)tr.GetObject(db.MLeaderStyleDictionaryId, OpenMode.ForRead);
  151.           if (mlStyles.Contains("Multileader"))
  152.           {
  153.             mlStyleId = mlStyles.GetAt("Multileader");
  154.           }
  155.  
  156.           tr.Commit();
  157.         }
  158.  
  159.         return mlStyleId;
  160.       }
  161.  
  162.       public static ObjectId GetMTextStyleObjectId()
  163.       {
  164.         var doc = Application.DocumentManager.MdiActiveDocument;
  165.         var ed = doc.Editor;
  166.         var db = doc.Database;
  167.         var tr = db.TransactionManager.StartTransaction();
  168.         ObjectId mlStyleId = ObjectId.Null;
  169.         using (tr)
  170.         {
  171.           TextStyleTable mlStyles = (TextStyleTable)tr.GetObject(db.TextStyleTableId, OpenMode.ForRead);
  172.           if (mlStyles.Has("Standard"))
  173.           {
  174.             mlStyleId = mlStyles["Standard"];
  175.           }
  176.           tr.Commit();
  177.         }
  178.  
  179.         return mlStyleId;
  180.       }
  181.     }
  182.  
  183.     public static void DirectionalLeader(string content, Point3d start, double width)
  184.     {
  185.       var doc = Application.DocumentManager.MdiActiveDocument;
  186.       var ed = doc.Editor;
  187.       var db = doc.Database;
  188.  
  189.       // Start a transaction, as we'll be jigging a db-resident object
  190.       using (var tr = db.TransactionManager.StartTransaction())
  191.       {
  192.         var bt = (BlockTable)tr.GetObject(db.BlockTableId, OpenMode.ForRead, false);
  193.         var btr = (BlockTableRecord)tr.GetObject(db.CurrentSpaceId, OpenMode.ForWrite, false);
  194.  
  195.         // Create and pass in an invisible MLeader
  196.  
  197.         // This helps avoid flickering when we start the jig
  198.         var ml = new MLeader();
  199.         ml.Visible = false;
  200.  
  201.         // Create jig
  202.         var jig = new DirectionalLeaderJig(content, start, ml, width);
  203.  
  204.         // Add the MLeader to the drawing: this allows it to be displayed
  205.         btr.AppendEntity(ml);
  206.         tr.AddNewlyCreatedDBObject(ml, true);
  207.  
  208.         // Set end point in the jig
  209.         var res = ed.Drag(jig);
  210.  
  211.         // If all is well, commit
  212.         if (res.Status == PromptStatus.OK)
  213.         {
  214.           tr.Commit();
  215.         }
  216.       }
  217.     }
  218.   }
  219. }
  220.  



Что не так?
Не забывайте про правильное Форматирование кода на форуме
Создание и добавление Autodesk Screencast видео в сообщение на форуме
Если Вы задали вопрос и на форуме появился правильный ответ, то не забудьте про кнопку Решение

Оффлайн AtomohodАвтор темы

  • ADN OPEN
  • ****
  • Сообщений: 453
  • Карма: 1
Александр, прошу прощения за мои ответы с запозданием - на работе завал. Большое спасибо за помощь. Решение в этом коде:

using (TextStyleTableRecord txtTblRec =
              mTextStyleId.Open(OpenMode.ForRead) as TextStyleTableRecord)
            {
              mt.TextHeight = txtTblRec.TextSize;
            }
У меня не получилось скорее всего потому, что я пошел совсем прямо - записал  mt.TextHeight = 600;

Оффлайн Александр Ривилис

  • Administrator
  • *****
  • Сообщений: 13829
  • Карма: 1784
  • Рыцарь ObjectARX
  • Skype: rivilis
У меня не получилось скорее всего потому, что я пошел совсем прямо - записал  mt.TextHeight = 600;
Это тоже должно было сработать, но вот если это значение слишком большое, то возможно текст не виден.
Не забывайте про правильное Форматирование кода на форуме
Создание и добавление Autodesk Screencast видео в сообщение на форуме
Если Вы задали вопрос и на форуме появился правильный ответ, то не забудьте про кнопку Решение

Оффлайн Привалов Дмитрий

  • ADN Club
  • *****
  • Сообщений: 533
  • Карма: 117
У меня не получилось скорее всего потому, что я пошел совсем прямо - записал  mt.TextHeight = 600;
Если есть время разобраться найди причину, почему не работало и поделись ;-)
Попробуй другое значение высоты
Поменяй порядок задания свойств Width, TextHeight, Contents, MText и др. В AutoCAD API такое бывает, что порядок важен, но нигде не описан.
Возможно аннотативность стилей как-то повлияла на отображение.

Оффлайн Дмитрий Загорулькин

  • ADN
  • *
  • Сообщений: 2531
  • Карма: 735
Позанудствую маленько :D
Код - C# [Выбрать]
  1. var mt = new MText();
Если мне не изменяет память, то мы как-то здесь на форуме уже обсуждали, что этот текст надо после использования "диспозить".

Оффлайн Александр Ривилис

  • Administrator
  • *****
  • Сообщений: 13829
  • Карма: 1784
  • Рыцарь ObjectARX
  • Skype: rivilis
Если мне не изменяет память, то мы как-то здесь на форуме уже обсуждали, что этот текст надо после использования "диспозить".
http://adn-cis.org/forum/index.php?topic=8775.msg34247#msg34247
Не забывайте про правильное Форматирование кода на форуме
Создание и добавление Autodesk Screencast видео в сообщение на форуме
Если Вы задали вопрос и на форуме появился правильный ответ, то не забудьте про кнопку Решение