我在Load
事件上画了一个圆圈,并且有两个按钮可以增加和减小圆圈的大小。但是我不能沿圆心缩小或放大大小。
private Draw draw = new Draw();
private int width = 150;
private int height = 150;
private int xLocation = 300;
private int yLocation = 100;
private void Form1_Load(object sender, EventArgs e)
{
}
protected override void OnPaint(PaintEventArgs e)
{
draw.circle(xLocation, yLocation, width, height, e.Graphics);
}
private void enlarge_Click_1(object sender, EventArgs e)
{
width = width + 5;
height = height + 5;
draw.circle(xLocation, yLocation, width, height, this.CreateGraphics());
}
private void Shrink_Click_1(object sender, EventArgs e)
{
width = width - 5;
height = height - 5;
draw.circle(xLocation, yLocation, height, height, this.CreateGraphics());
}
internal class Draw
{
public int x { get; set; }
public int y { get; set; }
public int width { get; set; }
public int height { get; set; }
public Graphics g { get; set; }
public void circle(int x, int y, int width, int height, Graphics g)
{
this.x = x;
this.y = y;
this.width = width;
this.height = height;
Pen color = new Pen(Color.Red);
this.g = g;
g.Clear(Color.White);
Rectangle circle = new Rectangle(x, y, width, height);
g.DrawEllipse(color, circle);
g.Dispose();
}
}
答案 0 :(得分:0)
使用Rectangle.Inflate方法在长轴的两个方向上放大或缩小Rectangle
。
您可以将width
,height
,xLocation
和yLocation
类成员替换为Rectangle
类型的单个变量,并在表单的实例中对其进行实例化。 Load
事件:
private Rectangle drawRect;
private void Form1_Load(object sender, EventArgs e)
{
//Set the default size and location...
drawRect = new Rectangle(
(ClientRectangle.Width - 150) / 2,
(ClientRectangle.Height - 150) / 2, 150, 150);
}
如果在Form
调整大小时需要重新调整绘图矩形的位置,请按以下方式处理Resize
事件:
private void Form1_Resize(object sender, EventArgs e)
{
//Assuming you want to center the drawing rectangle...
drawRect = new Rectangle(
(ClientRectangle.Width - drawRect.Width) / 2,
(ClientRectangle.Height - drawRect.Height) / 2,
drawRect.Width, drawRect.Height);
}
要放大和缩小尺寸:
private void enlarge_Click(object sender, EventArgs e)
{
var cr = ClientRectangle;
cr.Inflate(-50, -50);
//Optional check to draw within the ClientRectangle with some margins
if (cr.Contains(drawRect))
{
drawRect.Inflate(5, 5);
Invalidate();
}
}
private void Shrink_Click(object sender, EventArgs e)
{
//Optional check to have a minimum size for the Rectangle.
if (drawRect.Width >= 15 && drawRect.Height >= 15)
{
drawRect.Inflate(-5, -5);
Invalidate();
}
}
Draw
类可以简化为:
internal class Draw
{
public static void Circle(Graphics g, int x, int y, int width, int height) =>
Circle(g, new Rectangle(x, y, width, height));
public static void Circle(Graphics g, Rectangle rect)
{
g.Clear(Color.White);
g.DrawEllipse(Pens.Red, rect);
}
}
因此,您可以在任何Paint
事件中调用静态方法,就像这样简单:
private void Form1_Paint(object sender, PaintEventArgs e) =>
Draw.Circle(e.Graphics, drawRect);
旁注:
调用Control.Invalidate方法以通知绘图画布(在您的情况下为Form
)以刷新绘图/绘画例程并避免多余的调用。
没有理由在这种情况下创建新的Graphics
对象。
Pen
也是一次性物品,应丢弃。用于在using块中创建一次性对象,以为您完成此操作。