2

我想在 DataGridView 中我的一行的背景中显示一个冗长的旋转字符串。然而,这:

private void dataGridView1_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)
{
    if (e.RowIndex == 0)
    {
        ...
        //Draw the string
        Graphics g = dataGridView1.CreateGraphics();
        g.Clip = new Region(e.RowBounds);
        g.RotateTransform(-45);
        g.DrawString(printMe, font, brush, e.RowBounds, format);
    }
}

不起作用,因为文本在旋转之前被剪裁。

我也尝试过Bitmap第一次绘画,但绘画透明位图似乎有问题 - 文本是纯黑色的。

有任何想法吗?

4

1 回答 1

0

我想到了。问题是位图显然没有透明度,即使您使用PixelFormat.Format32bppArgb. 画线会导致它在黑色背景上绘制,这就是它如此黑暗的原因。

解决方案是将屏幕上的行复制到位图上,在位图上绘制,然后将其复制回屏幕。

g.CopyFromScreen(absolutePosition, Point.Empty, args.RowBounds.Size);

//Draw the rotated string here

args.Graphics.DrawImageUnscaledAndClipped(buffer, args.RowBounds);

以下是完整的代码清单供参考:

private void dataGridView1_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs args)
{
    if(args.RowIndex == 0)
    {
        Font font = new Font("Verdana", 11);
        Brush brush = new SolidBrush(Color.FromArgb(70, Color.DarkGreen));
        StringFormat format = new StringFormat
        {
            FormatFlags = StringFormatFlags.NoWrap | StringFormatFlags.NoClip,
            Trimming = StringTrimming.None,
        };

        //Setup the string to be printed
        string printMe = String.Join(" ", Enumerable.Repeat("RUNNING", 10).ToArray());
        printMe = String.Join(Environment.NewLine, Enumerable.Repeat(printMe, 50).ToArray());

        //Draw string onto a bitmap
        Bitmap buffer = new Bitmap(args.RowBounds.Width, args.RowBounds.Height);
        Graphics g = Graphics.FromImage(buffer);
        Point absolutePosition = dataGridView1.PointToScreen(args.RowBounds.Location);
        g.CopyFromScreen(absolutePosition, Point.Empty, args.RowBounds.Size);
        g.RotateTransform(-45, MatrixOrder.Append);
        g.TranslateTransform(-50, 0, MatrixOrder.Append); //So we don't see the corner of the rotated rectangle
        g.DrawString(printMe, font, brush, args.RowBounds, format);

        //Draw the bitmap onto the table
        args.Graphics.DrawImageUnscaledAndClipped(buffer, args.RowBounds);
    }
}
于 2010-04-09T20:17:11.557 回答