最近有TX产品用户提出了这样的需求,就是在TX文档插入图片之后,图片大小能够只适应其父容器的大小,比如在TextFrame中插入图片之后,图片的高和宽能够根据TextFrame的大小自动进行缩放比例的调整。本文就主要介绍该功能的实现方法。
实现,我们需要了解TX中的度量单位,TX中对象的度量单位是缇(Twip),而.NET中大多数使用的像素(Pixel),所以,我们第一步需要完成缇与像素之间的单位换算 1 Pixel = 1440 TPI / 96 DPI = 15 Twips,通过代码换算如下:
Graphics g = textControl1.CreateGraphics();int iTwipsPerPixel = (int)(1440 / g.DpiX);
图片插入,以及图片缩放比例代码如下:
private void InsertImage(){// 完成TX中使用的度量单位缇(Twip)与.NET使用的度量单位像素(Pixel)的转换
Graphics g = textControl1.CreateGraphics();int iTwipsPerPixel = (int)(1440 / g.DpiX);OpenFileDialog dlgOpen = new OpenFileDialog();
if (dlgOpen.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{// 加载图片
Image tmp = Image.FromFile(dlgOpen.FileName);// 获取图片父容器TextFrame
TXTextControl.TextFrame frame = textControl1.TextParts.GetMainText().TextFrames.GetItem(1000);// 创建TX中的图片对象
TXTextControl.Image image = new TXTextControl.Image(tmp);
// 设置图片ID
image.ID = 1001;//设置横向和纵向缩放比例属性,注意TextFrame中可用的空间范围应该减去Margin区域
image.HorizontalScaling = ((frame.Size.Width - frame.InternalMargins[0] - frame.InternalMargins[2]) * 100) / (tmp.Width * iTwipsPerPixel);image.VerticalScaling = ((frame.Size.Height - frame.InternalMargins[1] - frame.InternalMargins[3]) * 100) / (tmp.Height * iTwipsPerPixel);// 将图片插入到TextFrame中
textControl1.Images.Add(image, textControl1.InputPosition.TextPosition);}}
运行截图:
源码下载:VS2010+TX X9