Графический редактор - C# (237471)
Формулировка задачи:
Ребята, подскажите как реализовать рисование прямоугольника как в Paint. т.е. пока левая кнопка зажата, прямоугольник можно двигать, а когда пользователь отпускает кнопку мыши, то рисование прямоугольника завершается.....
Решение задачи: «Графический редактор»
textual
Листинг программы
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
DoubleBuffered = true;
}
struct RectangleParametres
{
public int X;
public int Y;
public int Width;
public int Height;
}
RectangleParametres[] RectParams = new RectangleParametres[0];
int X = 0;
int Y = 0;
private void Form1_MouseDown(object sender, MouseEventArgs e)
{
X = e.X;
Y = e.Y;
Array.Resize(ref RectParams, RectParams.Length + 1);
}
private void Form1_MouseMove(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
Bitmap bm = new Bitmap(Width, Height);
Graphics g = Graphics.FromImage(bm);
if (X < e.X)
{
RectParams[RectParams.Length - 1].Width = e.X - X;
RectParams[RectParams.Length - 1].X = X;
}
else
{
RectParams[RectParams.Length - 1].Width = X - e.X;
RectParams[RectParams.Length - 1].X = X - RectParams[RectParams.Length - 1].Width;
}
if (Y < e.Y)
{
RectParams[RectParams.Length - 1].Height = e.Y - Y;
RectParams[RectParams.Length - 1].Y = Y;
}
else
{
RectParams[RectParams.Length - 1].Height = Y - e.Y;
RectParams[RectParams.Length - 1].Y = Y - RectParams[RectParams.Length - 1].Height;
}
for (int i = 0; i < RectParams.Length; i++)
g.DrawRectangle(new Pen(Color.Black, 4), RectParams[i].X, RectParams[i].Y, RectParams[i].Width, RectParams[i].Height);
BackgroundImage = bm;
}
}
}
}