Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System.Windows;
- using System.Windows.Controls;
- using System.Windows.Input;
- using System.Windows.Media;
- using System.Windows.Shapes;
- namespace ShapeDrawingApp
- {
- public partial class MainWindow : Window
- {
- private enum DrawMode
- {
- None,
- Ellipse,
- Rectangle,
- Circle,
- Line
- }
- private DrawMode currentDrawMode = DrawMode.None;
- private Point startPoint;
- private Shape currentShape;
- public MainWindow()
- {
- InitializeComponent();
- }
- private void SetCurrentDrawMode(DrawMode mode)
- {
- currentDrawMode = mode;
- currentShape = null;
- }
- private void btnEllipse_Click(object sender, RoutedEventArgs e)
- {
- SetCurrentDrawMode(DrawMode.Ellipse);
- }
- private void btnRectangle_Click(object sender, RoutedEventArgs e)
- {
- SetCurrentDrawMode(DrawMode.Rectangle);
- }
- private void btnCircle_Click(object sender, RoutedEventArgs e)
- {
- SetCurrentDrawMode(DrawMode.Circle);
- }
- private void btnLine_Click(object sender, RoutedEventArgs e)
- {
- SetCurrentDrawMode(DrawMode.Line);
- }
- private void drawingCanvas_MouseDown(object sender, MouseButtonEventArgs e)
- {
- if (currentDrawMode != DrawMode.None)
- {
- startPoint = e.GetPosition(drawingCanvas);
- currentShape = CreateShape();
- drawingCanvas.Children.Add(currentShape);
- }
- }
- private void drawingCanvas_MouseUp(object sender, MouseButtonEventArgs e)
- {
- if (currentShape != null)
- {
- currentShape = null;
- }
- }
- private void drawingCanvas_MouseMove(object sender, MouseEventArgs e)
- {
- if (currentShape != null && e.LeftButton == MouseButtonState.Pressed)
- {
- Point currentPoint = e.GetPosition(drawingCanvas);
- UpdateShape(currentShape, startPoint, currentPoint);
- }
- }
- private Shape CreateShape()
- {
- Shape shape = null;
- switch (currentDrawMode)
- {
- case DrawMode.Ellipse:
- shape = new Ellipse();
- break;
- case DrawMode.Rectangle:
- shape = new Rectangle();
- break;
- case DrawMode.Circle:
- shape = new Ellipse();
- break;
- case DrawMode.Line:
- shape = new Line();
- break;
- }
- shape.Stroke = Brushes.Black;
- shape.StrokeThickness = 2;
- return shape;
- }
- private void UpdateShape(Shape shape, Point startPoint, Point endPoint)
- {
- if (shape == null)
- return;
- if (currentDrawMode == DrawMode.Line)
- {
- Line line = (Line)shape;
- line.X1 = startPoint.X;
- line.Y1 = startPoint.Y;
- line.X2 = endPoint.X;
- line.Y2 = endPoint.Y;
- }
- else
- {
- double left = Math.Min(startPoint.X, endPoint.X);
- double top = Math.Min(startPoint.Y, endPoint.Y);
- double width = Math.Abs(startPoint.X - endPoint.X);
- double height = Math.Abs(startPoint.Y - endPoint.Y);
- Canvas.SetLeft(shape, left);
- Canvas.SetTop(shape, top);
- if (currentDrawMode == DrawMode.Circle)
- {
- Ellipse ellipse = (Ellipse)shape;
- ellipse.Width = width;
- ellipse.Height = height;
- }
- else
- {
- shape.Width = width;
- shape.Height = height;
- }
- }
- }
- }
- }
Add Comment
Please, Sign In to add comment