【发布时间】:2011-07-05 00:57:29
【问题描述】:
是否可以在 WinForms 中以特定角度旋转按钮或任何控件?如果有,怎么做?
【问题讨论】:
-
请更具体。您还没有提到您的 GUI 工具包/框架,也没有具体说明“旋转”的含义(仅 90°?任何角度?)
-
旋转任意角度(90,180,...)
是否可以在 WinForms 中以特定角度旋转按钮或任何控件?如果有,怎么做?
【问题讨论】:
如果您真的想要(我不知道为什么会这样..*),您可以尝试使用Button 子类,可能是这样:
public partial class TurnButton : Button
{
public TurnButton()
{
InitializeComponent();
}
int angle = 0; // current rotation
Point oMid; // original center
protected override void OnLayout(LayoutEventArgs levent)
{
base.OnLayout(levent);
if (oMid == Point.Empty) oMid = new Point(Left + Width / 2, Top + Height / 2);
}
protected override void OnPaint(PaintEventArgs pe)
{
int mx = this.Size.Width / 2;
int my = this.Size.Height / 2;
SizeF size = pe.Graphics.MeasureString(Text, Font);
string t_ = Text;
Text = "";
base.OnPaint(pe);
if (!this.DesignMode)
{
Text = t_; pe.Graphics.TranslateTransform(mx, my);
pe.Graphics.RotateTransform(angle);
pe.Graphics.TranslateTransform(-mx, -my);
pe.Graphics.DrawString(Text, Font, SystemBrushes.ControlText,
mx - (int)size.Width / 2, my - (int)size.Height / 2);
}
}
protected override void OnClick(EventArgs e)
{
this.Size = new Size(Height, Width);
this.Location = new Point(oMid.X - Width / 2, oMid.Y - Height / 2);
angle = (angle + 90) % 360;
Text = angle + "°";
base.OnClick(e);
}
}
(* 我也不知道为什么要写这个;-)
【讨论】:
这与此处提出的问题类似: Rotating a .NET panel in Windows Forms
对该问题的答案的快速总结是,虽然有可能做到这一点,但它会非常非常复杂。
【讨论】:
在某些情况下可能的解决方法是:
使用 tabControl 并调整它的大小,以便您只剩下按钮。将对齐设置为左/右,您的按钮将旋转 90/270 度。
【讨论】:
public class VerticalButton : Button
{
public string VirticalText { get; set; }
protected override void OnPaint(PaintEventArgs pe)
{
base.OnPaint(pe);
StringFormat stringFormat = new StringFormat();
stringFormat.FormatFlags = StringFormatFlags.DirectionVertical;
SolidBrush solidBrush = new SolidBrush(this.ForeColor);
stringFormat.Alignment = StringAlignment.Center;
stringFormat.LineAlignment = StringAlignment.Center;
pe.Graphics.DrawString(VirticalText, this.Font, solidBrush,
new Rectangle(0, 0, Width, Height), stringFormat);
}
}
【讨论】: