.NET
cancel
Showing results for 
Show  only  | Search instead for 
Did you mean: 

How can I use a graphic ellipse with text together?

18 REPLIES 18
SOLVED
Reply
Message 1 of 19
kevinsir
1491 Views, 18 Replies

How can I use a graphic ellipse with text together?

Hello, everyone

I want to create a new order. when  using the order,It will create a  ellipse and  a DTEXT .I mean the ellipse and the DTEXT are a whole. when move the ellipse the DTEXT will alse move.However, users can  edit the  DTEXT.

Someone who can give  me some solution? Thanks very much!

18 REPLIES 18
Message 2 of 19
Hallex
in reply to: kevinsir

Hi Kevin,

Do you want to create the block with one attribute inside the ellipse?

_____________________________________
C6309D9E0751D165D0934D0621DFF27919
Message 3 of 19
Hallex
in reply to: kevinsir

Though you could be read same code in Labs,

here is quick example

    [CommandMethod("OrderBlock", CommandFlags.Modal | CommandFlags.Redraw)]
        public static void CreateOrderLabel()
        {
            // Get the current document and database
            Document doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;

            Database db = doc.Database;

            Editor ed = doc.Editor;

            using (Transaction tr = db.TransactionManager.StartTransaction())
            {
                try
                {
                    BlockTable bt = (BlockTable)tr.GetObject(db.BlockTableId, OpenMode.ForWrite);

                    // get current text size for attribute or use hard coded one instead
                    double txtheight = db.Textsize;
                    // block name
                    string blkName = "ORDER";
                    // check if exists
                    if (bt.Has(blkName))
                    {
                        ed.WriteMessage("\nBlock \"ORDER\" already exist.");
                        return;// if exists then exit
                    }
                    BlockTableRecord btr = (BlockTableRecord)tr.GetObject(db.CurrentSpaceId, OpenMode.ForWrite);
                    Point3d inspt = new Point3d(0, 0, 0);
                    BlockTableRecord newBtr = new BlockTableRecord();
                    bt.Add(newBtr);

                    // change settings for you block to your suit:
                    newBtr.Name = blkName;
                    newBtr.Origin = inspt;
                    newBtr.BlockScaling = BlockScaling.Uniform;
                    newBtr.Units = UnitsValue.Inches;
                    newBtr.Explodable = false;
                    tr.AddNewlyCreatedDBObject(newBtr, true);

                    Vector3d normal = Vector3d.ZAxis;
                    Vector3d majorAxis = 6 * txtheight * Vector3d.XAxis;// change major axis to your suit
                    double radiusRatio = 0.4;// change ratio to your suit
                    double startAng = 0.0;
                    double endAng = Math.PI * 2;
                    Ellipse ellipse = new Ellipse(inspt, normal, majorAxis, radiusRatio, startAng, endAng);
                    ellipse.Layer = "0";
                    ellipse.LinetypeId = db.ContinuousLinetype;
                    ellipse.Color = Autodesk.AutoCAD.Colors.Color.FromColorIndex(ColorMethod.ByAci, 0);// color by block
                    ellipse.LineWeight = LineWeight.LineWeight040;// wide lineweight 0.40, change on LineWeight.ByLineWeightDefault to discard it
                    newBtr.AppendEntity(ellipse);
                    tr.AddNewlyCreatedDBObject(ellipse, true);

                    AttributeDefinition attr = new AttributeDefinition();
                    attr.Layer = "0";
                    attr.LinetypeId = db.ContinuousLinetype;
                    attr.Color = Autodesk.AutoCAD.Colors.Color.FromColorIndex(ColorMethod.ByAci, 0);// color by block
                    attr.LineWeight = LineWeight.ByLineWeightDefault;
                    attr.Tag = "DESCRIPTION";
                    attr.Prompt = "Order description:";
                    attr.TextString = "blah";
                    attr.Preset = true;

                    //attr.TextStyle = db.Textstyle;//<--   A2009
                    attr.TextStyleId = db.Textstyle;//<--   A2010
                    attr.Height = txtheight;
                    attr.Position = inspt;
                    attr.Justify = AttachmentPoint.MiddleCenter;
                    attr.AlignmentPoint = inspt;
                    attr.LockPositionInBlock = true;
                    attr.AdjustAlignment(db);
                    newBtr.AppendEntity(attr);
                    tr.AddNewlyCreatedDBObject(attr, true);

                    tr.Commit();
                    ed.Regen();
                }
                catch (Autodesk.AutoCAD.Runtime.Exception ex)
                {
                    ed.WriteMessage(ex.Message + "\n" + ex.StackTrace);
                }
            }
        }

 

_____________________________________
C6309D9E0751D165D0934D0621DFF27919
Message 4 of 19
kevinsir
in reply to: kevinsir

Thanks for your repy.If the attribute can show  and edit on the paper , It is maybe perfect.

I will try your code.

Message 5 of 19
Hallex
in reply to: kevinsir

Here is VB.NET code,see my poor comments inline

        <CommandMethod("OrderBlock", CommandFlags.Modal Or CommandFlags.Redraw)> _
        Public Shared Sub CreateOrderLabel()
            ' Get the current document and database
            Dim doc As Document = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument

            Dim db As Database = doc.Database

            Dim ed As Editor = doc.Editor

            Using tr As Transaction = db.TransactionManager.StartTransaction()
                Try
                    Dim bt As BlockTable = DirectCast(tr.GetObject(db.BlockTableId, OpenMode.ForWrite), BlockTable)

                    ' get current text size for attribute or use hard coded one instead
                    Dim txtheight As Double = db.Textsize
                    ' block name
                    Dim blkName As String = "ORDER"
                    ' check if exists
                    If bt.Has(blkName) Then
                        ed.WriteMessage(vbLf & "Block ""ORDER"" already exist.")
                        ' if exists then exit
                        Return
                    End If
                    Dim btr As BlockTableRecord = DirectCast(tr.GetObject(db.CurrentSpaceId, OpenMode.ForWrite), BlockTableRecord)
                    Dim inspt As New Point3d(0, 0, 0)
                    Dim newBtr As New BlockTableRecord()
                    bt.Add(newBtr)

                    ' change settings for you block to your suit:
                    newBtr.Name = blkName
                    newBtr.Origin = inspt
                    newBtr.BlockScaling = BlockScaling.Uniform
                    newBtr.Units = UnitsValue.Inches
                    newBtr.Explodable = False
                    tr.AddNewlyCreatedDBObject(newBtr, True)

                    Dim normal As Vector3d = Vector3d.ZAxis
                    Dim majorAxis As Vector3d = 6 * txtheight * Vector3d.XAxis
                    ' change major axis to your suit
                    Dim radiusRatio As Double = 0.4
                    ' change ratio to your suit
                    Dim startAng As Double = 0.0
                    Dim endAng As Double = Math.PI * 2
                    Dim ellipse As New Ellipse(inspt, normal, majorAxis, radiusRatio, startAng, endAng)
                    ellipse.Layer = "0"
                    ellipse.LinetypeId = db.ContinuousLinetype
                    ellipse.Color = Autodesk.AutoCAD.Colors.Color.FromColorIndex(ColorMethod.ByAci, 0)
                    ' color by block
                    ellipse.LineWeight = LineWeight.LineWeight040
                    ' wide lineweight 0.40, change on LineWeight.ByLineWeightDefault to discard it
                    newBtr.AppendEntity(ellipse)
                    tr.AddNewlyCreatedDBObject(ellipse, True)

                    Dim attr As New AttributeDefinition()
                    attr.Layer = "0"
                    attr.LinetypeId = db.ContinuousLinetype
                    attr.Color = Autodesk.AutoCAD.Colors.Color.FromColorIndex(ColorMethod.ByAci, 0)
                    ' color by block
                    attr.LineWeight = LineWeight.ByLineWeightDefault
                    attr.Tag = "DESCRIPTION"
                    attr.Prompt = "Order description:"
                    attr.TextString = "blah"
                    attr.Preset = True
                    ' using current textstyle
                    'attr.TextStyle = db.Textstyle ''<--   A2009
                    attr.TextStyleId = db.Textstyle ''<--   A2010
                    attr.Height = txtheight
                    attr.Position = inspt
                    attr.Justify = AttachmentPoint.MiddleCenter
                    attr.AlignmentPoint = inspt
                    attr.LockPositionInBlock = True
                    attr.AdjustAlignment(db)
                    newBtr.AppendEntity(attr)
                    tr.AddNewlyCreatedDBObject(attr, True)

                    tr.Commit()
                    ed.Regen()
                Catch ex As Autodesk.AutoCAD.Runtime.Exception
                    ed.WriteMessage(ex.Message + vbLf + ex.StackTrace)
                End Try
            End Using
        End Sub

 

_____________________________________
C6309D9E0751D165D0934D0621DFF27919
Message 6 of 19
kevinsir
in reply to: Hallex

Thanks a lot ! It is a nice solution. However, is there any better idea that if i want to edit description on the screen directly,never show a description dialogue.Because my customers use CAD on the pad ,maybe they want a big input UI.

Message 7 of 19
Hallex
in reply to: kevinsir

In this case discard show dialog using ATTDIA variable, see Help file

Cheers 🙂

_____________________________________
C6309D9E0751D165D0934D0621DFF27919
Message 8 of 19
kevinsir
in reply to: Hallex

Can you tell me a more detailed method? Do  you mean that  when editing the attribute,  the dialogue also does not  appear ? 

Message 9 of 19
kevinsir
in reply to: kevinsir

I mean can I  use this attribute like dbtext,

and another question is that is therer any setting i can set the attibute or the ellipse to be  visible or invisible!

Message 10 of 19
Hallex
in reply to: kevinsir

I have not have a time for testing and could not reach at AutoCAD now,

but you can play with attribite mode,

say specify your settings instead, e.g. in this line of code:

attr.Preset = True

You may want to play with something like

attr.Verify=true, same for Visible etc

_____________________________________
C6309D9E0751D165D0934D0621DFF27919
Message 11 of 19
kevinsir
in reply to: Hallex

Thanks very much for your help ! I will try it !

Message 12 of 19
kevinsir
in reply to: kevinsir

Very greatful,Now I have another question.Is there any method to  access the AttributeDefinition or the ellipse of the block after having inserted the block into the paper. I want to set  AttributeDefinition visible or invisible dynamicly by code! 

Message 13 of 19


@kevinsir wrote:

... I want to set  AttributeDefinition visible or invisible dynamicly by code!  ...


AttributeDefinition or AttributeReference? AttributeDefinition is one for all BlockReference, but AttributeReference can be individual in every BlockReference.

Відповідь корисна? Клікніть на "ВПОДОБАЙКУ" цім повідомленням! | Do you find the posts helpful? "LIKE" these posts!
Находите сообщения полезными? Поставьте "НРАВИТСЯ" этим сообщениям!
На ваше запитання відповіли? Натисніть кнопку "ПРИЙНЯТИ РІШЕННЯ" | Have your question been answered successfully? Click "ACCEPT SOLUTION" button.
На ваш вопрос успешно ответили? Нажмите кнопку "УТВЕРДИТЬ РЕШЕНИЕ"


Alexander Rivilis / Александр Ривилис / Олександр Рівіліс
Programmer & Teacher & Helper / Программист - Учитель - Помощник / Програміст - вчитель - помічник
Facebook | Twitter | LinkedIn
Expert Elite Member

Message 14 of 19
Hallex
in reply to: kevinsir

You can set attribute invisible by click on attribute after insrting a block

here is quick example

   <CommandMethod("avis")> _
        Public Shared Sub SetAttributeVisibility()
            Dim doc As Document = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument

            Dim ed As Editor = doc.Editor

            Dim db As Database = doc.Database

            Dim ucs As Matrix3d = ed.CurrentUserCoordinateSystem

            Dim pno As New PromptNestedEntityOptions(vbLf & "Select an attribute inside an INSERT: ")

            Dim nres As PromptNestedEntityResult = ed.GetNestedEntity(pno)

            If nres.Status <> PromptStatus.OK Then
                ed.WriteMessage(vbLf & "Entsel failed")
                Return
            End If

            Try
                Dim tr As Transaction = db.TransactionManager.StartTransaction()

                Using tr
                    Dim pickPt As Point3d = nres.PickedPoint.TransformBy(ucs)

                    ed.WriteMessage(vbLf & "Picked point is {0}", pickPt)

                    Dim selId As ObjectId = nres.ObjectId

                    Dim objIds As New List(Of ObjectId)(nres.GetContainers())

                    ' Reverse the "containers" list

                    ' Now append the selected entity

                    objIds.Add(selId)

                    objIds.Reverse()

                    ' Retrieve the sub-entity path for this entity

                    Dim subEnt As New SubentityId(SubentityType.Null, 0)

                    Dim path As New FullSubentityPath(objIds.ToArray(), subEnt)

                    ' Open the outermost container, relying on the open

                    ' transaction...

                    Dim pSubEnt As Entity = TryCast(tr.GetObject(objIds(0), OpenMode.ForRead, False), Entity)

                    If Not pSubEnt.ObjectId.ObjectClass.IsDerivedFrom(RXClass.GetClass(GetType(AttributeReference))) Then Return

                    Dim attRef As AttributeReference = TryCast(tr.GetObject(pSubEnt.ObjectId, OpenMode.ForRead, False), AttributeReference)

                    If attRef Is Nothing Then Return

                    If attRef.Visible Then

                        ' ed.WriteMessage(vbLf & "The sub entity is of type {0}", pSubEnt.GetType().Name)

                        ' Get the object id of the owner block

                        Dim mainId As ObjectId = pSubEnt.OwnerId

                        Dim pOwner As DBObject = TryCast(tr.GetObject(mainId, OpenMode.ForRead, False), DBObject)

                        ' Output the class name of the owner block

                        ed.WriteMessage(vbLf & "The owner is of type {0}", pOwner.[GetType]().Name)

                        Dim pBlkName As String = String.Empty

                        ' Output the information of the block definition

                        Dim pBTR As BlockTableRecord = TryCast(pOwner, BlockTableRecord)

                        If pBTR IsNot Nothing Then

                            pBlkName = pBTR.Name

                            ed.WriteMessage(vbLf & "Block Record name is {0}", pBlkName)
                        End If
                        Dim pBref As BlockReference = TryCast(pOwner, BlockReference)
                        If pBref Is Nothing Then Return
                        pBref.UpgradeOpen()
                        attRef.UpgradeOpen()
                        attRef.Visible = False
                    End If

                    tr.Commit()
                End Using
            Catch ex As Autodesk.AutoCAD.Runtime.Exception
                ed.WriteMessage((vbLf + ex.Message & vbLf) + ex.StackTrace)

            Finally
            End Try
        End Sub

 

_____________________________________
C6309D9E0751D165D0934D0621DFF27919
Message 15 of 19

I am sorry that I mean the AttributeReference! Now I have find the 'AttributeCollection' Property of BlockReference which can access the Attribute. However, I have not find any Property of BlockReference to access the ellipse. Does it have any way to access it and set it visible or invisible?
Message 16 of 19


@kevinsir wrote:
...However, I have not find any Property of BlockReference to access the ellipse. Does it have any way to access it and set it visible or invisible?...

Ellipse is a part of BlockTableRecord and not part of BlockReference. You can have access to ellipse in BlockTableRecord and set it visible or invisible. But that setting will effect ALL BlockReference created from this BlockTableRecord (after regeneration of drawing).  If you create dynamic block you can manipulate property Visibility to hide/unhide ellipse and text individually in each BlockReference. Look at attached dwg-file.

Відповідь корисна? Клікніть на "ВПОДОБАЙКУ" цім повідомленням! | Do you find the posts helpful? "LIKE" these posts!
Находите сообщения полезными? Поставьте "НРАВИТСЯ" этим сообщениям!
На ваше запитання відповіли? Натисніть кнопку "ПРИЙНЯТИ РІШЕННЯ" | Have your question been answered successfully? Click "ACCEPT SOLUTION" button.
На ваш вопрос успешно ответили? Нажмите кнопку "УТВЕРДИТЬ РЕШЕНИЕ"


Alexander Rivilis / Александр Ривилис / Олександр Рівіліс
Programmer & Teacher & Helper / Программист - Учитель - Помощник / Програміст - вчитель - помічник
Facebook | Twitter | LinkedIn
Expert Elite Member

Message 17 of 19
kevinsir
in reply to: kevinsir

Aha,maybe dynamic block is which I needed。Thanks very much。I will try this way ! If your can give me some code for controlling dynamic block of C#,that will be perfect!

Message 18 of 19
kevinsir
in reply to: kevinsir

I am sorry that I have taken some time on the dynamic block .Howerver, there is a problem that how can I change the DBText 'test'  on your  attachment  ? I only have found a way to change it when  the block is defining. I try to create a new attribute when defining, but it is not shown on the paper.

Message 19 of 19
kevinsir
in reply to: kevinsir

I am so sorry that I have soloved the problem! I have not set the default vale . Thanks for all repies!

Can't find what you're looking for? Ask the community or share your knowledge.

Post to forums  

Autodesk DevCon in Munich May 28-29th


Autodesk Design & Make Report

”Boost