我创建了许多TextElement,需要对部分文字进行替换,代码如何实现呢?我已经能获取到TextBlock了,TextBlock提供有Replace函数,但不知道如何查找到要替近换的内容。
获取TextBlock中的文字内容,用C# 字符串操作函数去查找和替换。然后用创建的Text去Replace这个TextBlock。
-------------------------------------------------------------------
在C++的TextBlock下有专门的FindTextParameters和FindTextMatch两个类可用于此目的,但可惜的是.NET未做封装,C# 中无法使用。
TextQueryOptions queryOps = new TextQueryOptions(); List<Element> signatureElements = DgnHelper.GetElementsFromCell(libFileName, cellName); foreach (Element element in signatureElements) { if (element is TextElement) { TextElement text = element as TextElement; TextPartIdCollection tids = text.GetTextPartIds(queryOps); foreach (TextPartId tid in tids) { TextBlock block = text.GetTextPart(tid); string str = block.ToString(); str.Replace("{图号}", drawingNumber); block.ReplaceText(str, block.CreateStartCaret(), block.CreateEndCaret()); } } } CellHeaderElement cell = new CellHeaderElement(dgnModel, cellName, DPoint3d.Zero, DMatrix3d.Identity, signatureElements); DTransform3d t3d = DTransform3d.FromTranslation(new DPoint3d(w, y0, 0) * uor); cell.ApplyTransform(new TransformInfo(t3d)); cell.AddToModel();
嗯,按您的思路,重新编写了代码,基本实现了。感谢符老师。以下代码供网友参考:
using (ElementCopyContext copyContext = new ElementCopyContext(dgnModel)) { TransformInfo transform = new TransformInfo(DTransform3d.FromTranslation(new DPoint3d(w, y0, 0) * uor)); TextQueryOptions queryOps = new TextQueryOptions(); List<Element> signatureElements = DgnHelper.GetElementsFromCell(libFileName, cellName); foreach (Element element in signatureElements) { if (element is TextElement) { TextElement text = element as TextElement; TextPartIdCollection partIds = text.GetTextPartIds(queryOps); foreach (TextPartId partId in partIds) { TextBlock block = text.GetTextPart(partId); string str = block.ToString(); str = str.Replace("{图号}", drawingNumber); block.ReplaceText(str.Replace("{图号}", drawingNumber), block.CreateStartCaret(), block.CreateEndCaret()); text.ReplaceTextPart(partId, block); } } element.ApplyTransform(transform); copyContext.DoCopy(element); } }
文字替换的问题确实解决了,但出现了新问题,就是我原来的文字是水平居中的,现在替换后发现不能居中,这个是什么原因呢?
文字有一个属性叫做Justification(对齐方式),查看一下你替换前后该属性是否有变化?
另外,您使用的MSCE是哪个版本的?如果是Update10以及10之前的,这个Justification是有Bug的,需要您升级到最新版Update16测试一下。
对齐方式是正确的,CenterBaseline,然后CE Update14版本。
您安装有Update15或16吗?有可能这个文字功能的Bug修复是发生在Update15。我有点记不清楚具体版本了。
这个BUG,我在之前版本也有遇到。除了升级CE,还有其他办法么,比如有没有其他接口,可以支持类似在MS界面调用Find/Replace Text工具的函数,因为我发现用界面的工具去替换文字,是可以自动居中对齐的。
lingwei liu said:除了升级CE,还有其他办法么
可能需要改用老的C++的文字API去实现才行。
或者,您直接录制一个宏,升级为VBA代码后通过修改VBA代码去实现。这种方法就能调用到系统本身的功能了。
做了好多测试,发现ReplaceText后,TextBlock的UserOrigin发生了变化,所以在替换前获取这个UserOrigin,替换后再设置回去,就OK了。下面是代码,供大家参考
DPoint3d oldUserOrigin = block.GetUserOrigin();//替换前获取 block.ReplaceText(str, block.CreateStartCaret(), block.CreateEndCaret()); block.SetUserOrigin(oldUserOrigin);//替换后设置回去
谢谢分享。注意这个问题在不同版本中的表现可能是不同的。新版本应该不需要这种补救措施了。