【问题标题】:Displaying a rotated string - DataGridView.RowPostPaint显示旋转的字符串 - DataGridView.RowPostPaint
【发布时间】:2011-02-06 06:58:20
【问题描述】:

我想在 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 上绘画,但绘画透明位图似乎有问题 - 文本显示为纯黑色。

有什么想法吗?

【问题讨论】:

    标签: c# graphics datagridview paint clipping


    【解决方案1】:

    我想通了。问题是位图显然没有透明度,即使您使用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);
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2016-05-23
      • 1970-01-01
      • 2022-11-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-10-21
      • 2018-07-14
      相关资源
      最近更新 更多