← 返回所有博客文章

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)