2010-04-09 56 views
2

我想在DataGridView中的我的行之一的背景中顯示一個冗長的旋轉字符串。然而,這樣的:顯示一個旋轉的字符串 - DataGridView.RowPostPaint

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上繪畫,但是繪製透明位圖似乎存在問題 - 文字是純黑色的。

任何想法?

回答

0

我想通了。問題是Bitmaps顯然沒有透明度,即使在使用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); 
    } 
} 
相關問題