c#cad 创建-文本(一)
运行环境 vs2022 c# cad2016 调试成功
一、代码说明
该代码是一个用于在AutoCAD中创建文本的命令。
首先,通过添加using语句引用了需要使用的Autodesk.AutoCAD命名空间。
然后,在命名空间CreateTextInCad下定义了一个名为CreateTextCommand的类,用于实现创建文本的命令。
在CreateTextCommand类中,使用[CommandMethod]特性定义了一个名为CreateText的命令方法。这个方法将在AutoCAD中执行创建文本的操作。
在CreateTextCommand方法中,首先获取当前活动文档的Document对象、数据库对象、编辑器对象,以及启动一个事务Transaction。
然后,通过BlockTableId获取模型空间的BlockTableRecord对象。
接下来,定义了一个起始位置startPoint和要创建的文本内容textContent。
通过使用using语句创建一个新的事务,并在事务中执行具体的操作。
在事务中,首先创建一个Text3d对象,并将其添加到模型空间中。
然后,使用tr.AddNewlyCreatedDBObject方法将新创建的文本对象添加到事务中,以便在提交事务时进行保存。
最后,在编辑器中输出一条消息,表示文本已成功创建。
整个过程在一个事务中进行,以确保对数据库的修改是具有原子性的,即要么全部执行成功,要么全部回滚。
代码最后通过[assembly: CommandClass(typeof(CreateTextInCad.CreateTextCommand))]特性将CreateTextCommand类注册为AutoCAD命令。
用户在AutoCAD中可以通过输入CreateText命令来执行这段代码创建文本。
二、完整代码
using System;
using Autodesk.AutoCAD.ApplicationServices;
using Autodesk.AutoCAD.EditorInput;
using Autodesk.AutoCAD.DatabaseServices;
using Autodesk.AutoCAD.Geometry;
[assembly: CommandClass(typeof(CreateTextInCad.CreateTextCommand))]
namespace CreateTextInCad
{
public class CreateTextCommand
{
[CommandMethod("CreateText")]
public void CreateTextCommand()
{
Document doc = Application.DocumentManager.MdiActiveDocument;
Database db = doc.Database;
Editor ed = doc.Editor;
Transaction tr = db.TransactionManager.StartTransaction();
BlockTable bt = tr.GetObject(db.BlockTableId, OpenMode.ForRead) as BlockTable;
BlockTableRecord btr = tr.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForWrite) as BlockTableRecord;
Point3d startPoint = new Point3d(0, 0, 0); // 文本起始位置
string textContent = "Hello, AutoCAD!"; // 要创建的文本内容
using (tr)
{
// 创建文本对象并添加到模型空间中
Text3d textEntity = new Text3d(startPoint, textContent);
btr.AppendEntity(textEntity);
tr.AddNewlyCreatedDBObject(textEntity, true);
ed.WriteMessage("\n文本已创建!");
}
}
}
}
图例

三、文本属性
using Autodesk.AutoCAD.DatabaseServices; // 创建一个新的DBText对象 DBText text = new DBText(); // 设置属性 text.Content = "Hello, World!"; text.Position = new Point3d(0, 0, 0); text.Height = 2.5; text.Style = "Standard";
主要的属性:
-
Content: 获取或设置文字的内容,即实际显示的文本字符串。
-
Position: 获取或设置文字对象的插入点,这是一个三维坐标点。
-
Height: 获取或设置文字的高度。
-
Rotation: 获取或设置文字的旋转角度。
-
Style: 获取或设置用于文字的对象文字样式。
-
WidthFactor: 获取或设置文字的宽度因子,影响文字相对于其样式定义的默认宽度的缩放比例。
-
Justify: 获取或设置文字的对齐方式,例如左对齐、居中对齐或右对齐等。
//感谢大家的点赞,收藏,转发,关注
本文来自网络,不代表协通编程立场,如若转载,请注明出处:https://net2asp.com/eba1b00a0e.html
