代码之家  ›  专栏  ›  技术社区  ›  BlueRaja - Danny Pflughoeft

显示旋转的字符串-DataGridView.RowPostpaint

  •  2
  • BlueRaja - Danny Pflughoeft  · 技术社区  · 15 年前

    我想在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 首先,但是在绘制透明位图时似乎有一个问题——文本是纯黑色的。

    有什么想法吗?

    1 回复  |  直到 15 年前
        1
  •  0
  •   BlueRaja - Danny Pflughoeft    15 年前

    我知道了。问题是位图显然没有透明度,即使使用 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);
        }
    }
    
    推荐文章