Spread 图文混排单元格类型实现方法之一

发布时间:2013/01/22 00:01 发布者:jian

返回博客中心

Spread for WinForms 中提供了 TextCellType 和 ImageCellType 两种单元格类型,可分别用于文字和图片类型的单元格,不过有时也希望在单元格中同时显示文字和图片,今天就使用自定义单元格类型来实现图文混排效果。

首先,我们需要从 ImageCellType 继承实现一个自定义单元格类型 ImageTextCellType,并重写 PaintCell 方法,代码如下:

    public class ImageTextCellType : FarPoint.Win.Spread.CellType.ImageCellType
    {
        private Picture picture;

        public ImageTextCellType()
        {
            picture = new Picture();
        }

        public override void PaintCell(Graphics g, Rectangle r, FarPoint.Win.Spread.Appearance appearance, object value, bool isSelected, bool isLocked, float zoomFactor)
        {
            if (value != null)
            {
                Image image = value as Image;
                string strValue = image.Tag.ToString();//文字

                SolidBrush brush = new SolidBrush(Color.White);
                GraphicsState gstate = g.Save();
                g.IntersectClip(r);
                g.FillRectangle(brush, r);
                brush.Dispose();

                if (image != null)
                {
                    Rectangle rectangle = new Rectangle(new Point(r.X, r.Y), new Size(200, 200));
                    if (rectangle == Rectangle.Empty)
                    {
                        g.Restore(gstate);
                        return;
                    }
                    picture.Image = image;
                    picture.Paint(g, rectangle.X, rectangle.Y, rectangle.Width, rectangle.Height);
                    SizeF size = g.MeasureString(strValue, appearance.Font);
                    g.DrawString(strValue, appearance.Font, new SolidBrush(Color.Black), new PointF(r.X, r.Y + image.Size.Height + 5));
                }
                g.Restore(gstate);
            }
            else
            {
                base.PaintCell(g, r, appearance, value, isSelected, isLocked, zoomFactor);
            }
        }
    }

 

接下来在Spread中使用 ImageTextCellType 单元格类型,代码如下:

    private void Form1_Load(object sender, EventArgs e)
    {
        ImageTextCellType itct = new ImageTextCellType();

        fpSpread1.ActiveSheet.Columns[0].CellType = itct;

        Image image = Image.FromFile(Application.StartupPath + @"\Images\八仙花.jpg");
        image.Tag = "八仙花";
        fpSpread1.ActiveSheet.Cells[0, 0].Value = image;

        image = Image.FromFile(Application.StartupPath + @"\Images\灯塔.jpg");
        image.Tag = "灯塔";
        fpSpread1.ActiveSheet.Cells[1, 0].Value = image;
    }

 

运行截图:

 

 

源码下载:

7719_ImageText.zip (196.07 kb)


关于葡萄城

赋能开发者!葡萄城是专业的集开发工具、商业智能解决方案、低代码开发平台于一身的软件和服务提供商,为超过 75% 的全球财富 500 强企业提供服务。葡萄城专注控件软件领域30年,希望通过模块化的开发控件、灵活的低代码应用开发平台等一系列开发工具、解决方案和服务,帮助开发者快速响应复杂多变的业务需求,最大程度地发挥开发者的才智和潜能,让开发者的 IT 人生更从容更美好。

了解详情,请访问葡萄城官网