Auto CAD二次开发——文字样式

学如逆水行舟,不进则退。 愿自己不忘初心,坚持积累。感谢大家的支持。本篇博客主要是学习文字样式。个人向来喜欢琢磨这类实用技能,每次刷视频看到博主们自制的各类辅助工具,都觉得特别厉害。自己也想试着动手尝试,不求做到多专业,核心是能实现一些自己需要的功能,不让 CAD 这项技能在手里慢慢荒废,在实践中慢慢成长就好。

目录

1、基础知识储备

2、核心代码以及封装函数调用

[2.1 文本样式函数封装](#2.1 文本样式函数封装)

[2.2 文字样式封装函数的调用](#2.2 文字样式封装函数的调用)

[2.3 运行结果:](#2.3 运行结果:)

[2.4 从DBText关联的文字样式中同步属性到DBText对象](#2.4 从DBText关联的文字样式中同步属性到DBText对象)


1、基础知识储备

在实际的CAD使用中,我们避免不了会写文字进行对图解释,这些文字如何通过代码实现,这是我们学习的关键:

1、通过查看其父级引用,可以发现其DBText属于 Entity,与之前学习绘制圆弧、直线等内容同属于一个父类,那么就可以仿照之前的思路进行编写。

2、这篇主要对创建文字样式的几种类型进行封装,包括:(文字样式、字体文件名和大字体文件名创建文字样式)、(文字样式、字体文件名创建文字样式)(字样式、字体文件名,可以加粗、倾斜,使用字体的字符集,字体的字宽和语义定义创建文字样式)。

3、对封装函数的调用。

Database 对象包括所有的图形和大部分非图形的 AutoCAD 对象。 被包含在 Database 中的一些对象有实体,符号表,命名字典。实体在 Database 中表示图纸内部的图形对象。直线、圆、圆弧、文本、填充和多段线都是实体的一个例子。用户可以在屏幕上看到一个实体并可以操作它。用户通过 Document 对象的 Database 成员属性可以访问当前文档的 Database 对象。
文本DBText的继承关系:DBText(文本)->Entity(实体)->DBObject(基础数据对象)->Drawable(图形)->RXObject

2、核心代码以及封装函数调用

2.1 文本样式函数封装

cs 复制代码
/// <summary>
/// 将图形对象添加到图形对象中
/// </summary>
/// <param name="db">图形数据库</param>
/// <param name="ent">图形对象,可变参数</param>
/// <returns>图形的objectId,数组返回</returns>
public static ObjectId[] AddEntityToModelSpace(this Database db, params Entity[] ent)

/// <summary>
/// 字体字符集,0(英文)、1(与当前操作系统语言有关)、134(简体中文)、136(繁体中文)、255(与操作系统有关)。
/// </summary>
public enum FontCharSet


/// <summary>
/// 字体的字宽可以取值为:0(默认字宽)、1(固定字宽)、2(可变字宽)
/// </summary>
public enum FontPitch

/// <summary>
/// 字体的语系定义可以取值为:0(使用默认字体)、16(可变的笔画宽度,有衬线,如MS Serif字体)、32(可变的笔画宽度,无衬线,如MSSansSerif字体)、48(固定笔画宽度,衬线可以有也可以没有,如Courier New字体)、64(手写体,如Cursive 字体)、80(小说字体,如旧式英语)。
/// </summary>
public enum FontFamily

/// <summary>
/// 创建文字样式
/// </summary>
/// <param name="db">图形数据库</param>
/// <param name="styleName">文字样式</param>
/// <param name="fontFilename">字体文件名</param>
/// <param name="bigFontFilename">大字体文件名</param>
/// <returns>字体的ObjectId</returns>
public static ObjectId AddTextStyle(this Database db, string styleName, string fontFilename, string bigFontFilename)

/// <summary>
/// 创建文字样式,无大字体文字样式
/// </summary>
/// <param name="db">图形数据库</param>
/// <param name="styleName">文字样式</param>
/// <param name="fontFilename">字体文件名</param>
/// <returns>字体的ObjectId</returns>
public static ObjectId AddTextStyle(this Database db, string styleName, string fontFilename)

/// <summary>
/// 创建字体(可以加粗、倾斜)
/// </summary>
/// <param name="db">图形数据库</param>
/// <param name="styleName">文字样式</param>
/// <param name="fontName">字体文件名</param>
/// <param name="bold">是否加粗</param>
/// <param name="italic">是否倾斜</param>
/// <param name="charset">字体的字符集,具体参考FontCharSet</param>
/// <param name="pitchAndFamily">字体的字宽和语义定义</param>
/// <returns></returns>
public static ObjectId AddTextStyle(this Database db, string styleName, string fontName, bool bold, bool italic, int charset, int pitchAndFamily)

/// <summary>
/// 设置文字属性
/// </summary>
/// <param name="styleId">文字样式</param>
/// <param name="textSize">文字高度</param>
/// <param name="xscale">宽度因子</param>
/// <param name="obliguingAngle">倾斜角度</param>
/// <param name="isVertical">是否垂直</param>
/// <param name="upsideDown">是否上下颠倒</param>
/// <param name="backwards">是否反向</param>
/// <param name="annotative">是否具有注释</param>
/// <param name="paperOrientation">文字方向是否与布局匹配</param>
public static void SetTextStyleProp(this ObjectId styleId, double textSize, double xscale, double obliguingAngle, bool isVertical, bool upsideDown, bool backwards, AnnotativeStates annotative, bool paperOrientation)

2.2 文字样式封装函数的调用

cs 复制代码
using Autodesk.AutoCAD.ApplicationServices;
using Autodesk.AutoCAD.DatabaseServices;
using Autodesk.AutoCAD.EditorInput;
using Autodesk.AutoCAD.Geometry;
using Autodesk.AutoCAD.Runtime;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using UserDateBase;

namespace CAD_TabDeme
{
    public class TextStyle
    {
        [CommandMethod("NewStyle")]
        public void Newstyle()
        {
            Database db = HostApplicationServices.WorkingDatabase;
            Editor ed = Application.DocumentManager.MdiActiveDocument.Editor;
            //设置ruerype字体(体)
            ObjectId styleId = db.AddTextStyle("仿宋体", "simfang.ttf");
            DBText txt1 = new DBText();
            txt1.TextString = "仿宋体";
            txt1.TextStyleId = styleId;//文字样式
            txt1.Position = new Point3d(0, 50, 0); // 新增位置,避免重叠

            //设置SHX字体(romans)
            styleId = db.AddTextStyle("罗马字体", "romans", "gbcbig");
            DBText txt2 = new DBText();
            txt2.TextString = "罗马字体";
            txt2.TextStyleId = styleId;//文字样式
            txt2.Position = new Point3d(0, 40, 0); // 新增位置

            //设置SHX字体(romans)
            styleId = db.AddTextStyle("垂直罗马字体", "romans", "gbcbig");
            //设置文字样式的各种属性
            styleId.SetTextStyleProp(2.0, 0.67, 15 * Math.PI / 180, true, true, true, AnnotativeStates.True, true);
            DBText txt3 = new DBText();
            txt3.TextString = "垂直罗马字体";
            txt3.TextStyleId = styleId;
            txt3.Position = new Point3d(0, 30, 0); // 新增位置

            //设置Truerype字体(宋体),并且有加粗、倾斜效果
            styleId = db.AddTextStyle("加粗斜宋体", "宋体", true, true, 0, 0);
            DBText txt4 = new DBText();
            txt4.TextString = "加粗斜宋体";
            txt4.TextStyleId = styleId;
            txt4.Position = new Point3d(0, 20, 0); // 新增位置
            db.AddEntityToModelSpace(txt1, txt2, txt3, txt4);

            ed.WriteMessage("\n文字样式及示例文字已成功创建。");
        }
    }
}

2.3 运行结果:

以上内容主要参考的是AutoCADVBA&VB.NET开发基础与实例教程(第二版)曾洪飞、卢择临、张帆编著的书籍学习,但是封装函数内部并不完全相同,封装成更符合自己的样式(下边是我第一次用C#封装函数可能有点不好,仅供大家参考)。

2.4 从DBText关联的文字样式中同步属性到DBText对象

文字样式的注释性、高度、宽度因子、倾斜角度、颠倒、反向等属性不会作用到文字中,但可以通过设置文字的有关属性来对应文字样式的属性。用于设置单行文本的属性为当前文字样式的属性,代码如下:

cs 复制代码
/// <summary>
        /// 从DBText关联的文字样式中同步属性到DBText对象
        /// 同步内容:倾斜角、注释性、纸张方向、宽度因子、高度、镜像状态(颠倒/反向)
        /// 核心逻辑:绕开原有对象状态限制,通过ObjectId重新打开对象确保可写,兼容已提交到模型空间的DBText
        /// </summary>
        /// <param name="txt">需要同步属性的DBText对象(需关联有效文字样式)</param>
        public static void SetFromTextStyle(this DBText txt)
        {
            Database db = txt.Database;

            // 启动事务:所有数据库对象操作必须在事务内执行,确保数据一致性
            using (Transaction trans = db.TransactionManager.StartTransaction())
            {
                // 1. 通过DBText的文字样式ID,以只读模式打开关联的文字样式表记录
                // 目的:获取文字样式中定义的基础属性(倾斜角、宽度因子等),只读模式不影响其他操作
                TextStyleTableRecord str = txt.TextStyleId.GetObject(OpenMode.ForRead) as TextStyleTableRecord;

                // 2. 关键步骤:通过DBText的ObjectId,以写模式重新打开对象
                // 原因:原有txt对象可能处于只读状态(如已提交到模型空间),直接升级状态易报错
                // 效果:绕开原有状态限制,确保能修改DBText的属性
                DBText txtWrite = txt.ObjectId.GetObject(OpenMode.ForWrite) as DBText;
                
                // 3. 同步倾斜角:从文字样式获取倾斜角(单位:弧度),赋值给DBText
                txtWrite.Oblique = str.ObliquingAngle;//设置倾斜角(弧度)
                // 4. 同步注释性状态:保持DBText与文字样式的注释性一致(是否支持注释缩放)
                txtWrite.Annotative = str.Annotative;//设置文字的注释性
                // 5. 同步纸张方向:文字方向是否与布局匹配(PaperOrientation为ushort类型,非0即true)
                txtWrite.SetPaperOrientation(Convert.ToBoolean(str.PaperOrientation));
                // 6. 同步宽度因子:控制文字的水平缩放比例(1.0为默认宽度)
                txtWrite.WidthFactor = str.XScale;//设置宽度比例
                // 7. 同步文字高度:优先使用文字样式定义的高度;若样式高度为0(CAD默认动态高度),则设置默认值3.5
                if (str.TextSize==0)
                {
                    txtWrite.Height = 3.5;
                }
                else
                {
                    txtWrite.Height = str.TextSize;//设置高度
                }
                // 8. 同步镜像状态:根据文字样式的FlagBits(标志位)判断是否颠倒/反向
                // FlagBits位掩码定义:2=上下颠倒,4=水平反向,6=颠倒+反向
                if (str.FlagBits == 2)// 仅上下颠倒
                {
                    txtWrite.IsMirroredInX = true;// X轴镜像(上下颠倒)
                }
                else if (str.FlagBits == 4)// 仅水平反向
                {
                    txtWrite.IsMirroredInY = true;// Y轴镜像(水平反向)
                }
                else if (str.FlagBits == 6)// 颠倒且反向(2+4=6)
                {
                    txtWrite.IsMirroredInX = txtWrite.IsMirroredInY = true;
                }
                // 提交事务:确认所有属性修改,写入数据库(事务内修改仅提交后生效)
                trans.Commit();
            }
        }

运行结果

cs 复制代码
txt3.SetFromTextStyle();
相关推荐
智者知已应修善业2 小时前
【c# 想一句话把 List<List<string>>的元素合并成List<string>】2023-2-9
经验分享·笔记·算法·c#·list
FuckPatience3 小时前
C# 接口隔离的一个案例
c#
津津有味道4 小时前
Ntag 424 DNA写入URI网址配置开启动态UID计数器镜像C#源码
c#·uri·ndef·424dna·动态uid·计数器镜像
万19997 小时前
asp.net core webapi------3.AutoMapper的使用
c#·.netcore
唐青枫8 小时前
C#.NET 路由机制深入解析:从传统路由到 Endpoint Routing
c#·.net
hixiong12318 小时前
C# OpenCVSharp使用 读光-票证检测矫正模型
人工智能·opencv·c#
霜绛18 小时前
C#知识补充(二)——命名空间、泛型、委托和事件
开发语言·学习·unity·c#
好望角雾眠18 小时前
第四阶段C#通讯开发-6:Socket之UDP
开发语言·笔记·学习·udp·c#
霜绛20 小时前
C#知识补充(一)——ref和out、成员属性、万物之父和装箱拆箱、抽象类和抽象方法、接口
开发语言·笔记·学习·c#