i am a begginer at ui design and windows forms in general. And i am encountering some issues when designing a custom control control
The issue that i am having is that windows forms is not fitting my control properly
Here is how it looks:
Even by disabling AutoSize, it still looks wrong.
Again, i am not very experienced, and i watched a tutorial to make this switch button.
As you can see, the edges of the circle are completly cut, and i dont know why
Here is the code:
public AzTogglebutton()
{
this.AutoSize = true;
this.MinimumSize = new Size(50, 22);
}
private GraphicsPath GetFigurePath()
{
int arcSize = this.Height - 1;
Rectangle leftArc = new Rectangle(0, 0, arcSize, arcSize);
Rectangle rightArc = new Rectangle(this.Width - arcSize - 2, 0, arcSize, arcSize);
GraphicsPath path = new GraphicsPath();
path.StartFigure();
path.AddArc(leftArc, 90, 180);
path.AddArc(rightArc, 270, 180);
path.CloseFigure();
return path;
}
protected override void OnPaint(PaintEventArgs pevent)
{
int toggleSize = this.Height 3;
pevent.Graphics.SmoothingMode = SmoothingMode.AntiAlias;
pevent.Graphics.Clear(this.Parent.BackColor);
if (this.Checked) //ON
{
//Draw the control surface
if (solidStyle)
pevent.Graphics.FillPath(new SolidBrush(onBackColor), GetFigurePath());
else pevent.Graphics.DrawPath(new Pen(onBackColor, 2), GetFigurePath());
//Draw the toggle
pevent.Graphics.FillEllipse(new SolidBrush(onToggleColor),
new Rectangle(this.Width - this.Height - 2, -2, toggleSize, toggleSize));
}
else //OFF
{
//Draw the control surface
if (solidStyle)
pevent.Graphics.FillPath(new SolidBrush(offBackColor), GetFigurePath());
else pevent.Graphics.DrawPath(new Pen(offBackColor, 2), GetFigurePath());
//Draw the toggle
pevent.Graphics.FillEllipse(new SolidBrush(offToggleColor),
new Rectangle(-2, -2, toggleSize, toggleSize));
}
}
CodePudding user response:
I made some adjustments to the size you are using:
private GraphicsPath GetFigurePath()
{
var arcSize = this.ClientSize.Height;
var leftArc = new Rectangle(0, 0, arcSize, arcSize - 1);
var rightArc = new Rectangle(this.ClientSize.Width - arcSize - 1, 0, arcSize, arcSize - 1);
var path = new GraphicsPath();
path.StartFigure();
path.AddArc(leftArc, 90, 180);
path.AddArc(rightArc, 270, 180);
path.CloseFigure();
return path;
}
For consistency, I would continue to use a GraphicsPath to draw the highlight circle:
private GraphicsPath GetOnPath()
{
var arcSize = this.ClientSize.Height;
var leftArc = new Rectangle(0, 0, arcSize, arcSize - 1);
var rightArc = new Rectangle(0, 0, arcSize, arcSize - 1);
var path = new GraphicsPath();
path.StartFigure();
path.AddArc(leftArc, 90, 180);
path.AddArc(rightArc, 270, 180);
path.CloseFigure();
return path;
}
The end result:
pevent.Graphics.Clear(this.Parent.BackColor);
pevent.Graphics.SmoothingMode = SmoothingMode.AntiAlias;
pevent.Graphics.FillPath(new SolidBrush(offBackColor), GetFigurePath());
pevent.Graphics.FillPath(new SolidBrush(offToggleColor), GetOnPath());