2010-06-30 103 views
0

我試圖旋轉90度的標籤。目前我可以從標籤中取文字並旋轉,但我想要做的事實際上是旋轉我選擇的標籤,或者如果我真的很華麗,可以說一個按鈕控件。因此,使用下面的代碼,我該如何修改它,以便我可以給它一個控件並讓它旋轉呢?將標籤文本和按鈕旋轉90度

protected override void OnPaint(PaintEventArgs e) 
    { 
     Graphics graphics = e.Graphics; 

     string text = label4.Text; 

     StringFormat stringFormat = new StringFormat(); 
     stringFormat.Alignment = StringAlignment.Center; 
     stringFormat.Trimming = StringTrimming.None; 

     Brush textBrush = new SolidBrush(this.ForeColor); 

     //Getting the width and height of the text, which we are going to write 
     float width = graphics.MeasureString(text, this.Font).Width; 
     float height = graphics.MeasureString(text, this.Font).Height; 

     //The radius is set to 0.9 of the width or height, b'cos not to 
     //hide and part of the text at any stage 
     float radius = 0f; 
     if (ClientRectangle.Width < ClientRectangle.Height) 
     { 
      radius = ClientRectangle.Width * 0.9f/2; 
     } 
     else 
     { 
      radius = ClientRectangle.Height * 0.9f/2; 
     } 
     int rotationAngle = 90; 
     double angle = (rotationAngle/180) * Math.PI; 
     graphics.TranslateTransform(
      (ClientRectangle.Width + (float)(height * Math.Sin(angle)) - (float)(width * Math.Cos(angle)))/2, 
      (ClientRectangle.Height - (float)(height * Math.Cos(angle)) - (float)(width * Math.Sin(angle)))/2); 
     graphics.RotateTransform((float)rotationAngle); 
     graphics.DrawString(text, this.Font, textBrush, 0, 0); 
     graphics.ResetTransform();   
    } 

回答

0

你可以使用WPF代替的WinForms ...那麼它的簡單變換;)

+1

我做到了,但是這打開了一個全新的蠕蟲罐...... – flavour404 2010-07-05 20:50:39

4

標準Windows窗體控件(如標籤和按鈕)操作系統本身,Windows窗體呈現不做實際的繪圖。

因此,不幸的是,您無法控制諸如旋轉和縮放這些類型的控件。這只是Windows窗體本身的限制,也是微軟創建WPF的主要原因之一。

WPF控件是完全由WPF呈現(在後臺使用DirectX)。 WPF支持所有標準2D(和3D)轉換,如縮放,旋轉和平移。

其實在windows窗體中,您可以創建自定義控件,使用GDI +進行渲染,並且可以根據需要進行旋轉和縮放。當然,現在你自己做所有的工作,看起來不是你想要的。