Ross Baker
Ross Baker

Reputation: 13

How to get rectangle position by coordinate in wpf canvas

I have some coordinates for drawing a rectangle. For example A(146,557), B(1499,557), C(1499,637), D(146,637).

How can I draw a rectangle in WPF using coordinates?

Rectangle myRectangle = new Rectangle();
double rectangleHeight = RectangleHeight(146,557,1499,557,1499,637,146,637);
double rectangleWidth = RectangleWidth(146,557,1499,557,1499,637,146,637);
myRectangle.Height = rectangleHeight;
myRectangle.Width = rectangleWidth;
SolidColorBrush partiallyTransparentSolidColorBrush = new SolidColorBrush(Colors.Green);
partiallyTransparentSolidColorBrush.Opacity = 0.25;
myRectangle.Fill = partiallyTransparentSolidColorBrush;
canvas.Children.Insert(0, myRectangle);
Canvas.SetTop(myRectangle, rectangleHeight);
Canvas.SetLeft(myRectangle, rectangleWidth);

Here are my methods for getting the height and width.

private double RectangleHeight(int h1, int h2, int h3, int h4, int h5, int h6, int h7, int h8) {
    int a1 = h1 - h7;
    int a2 = h2 - h8;
    int b1 = a1 * a1;
    int b2 = a2 * a2;
    double sqt1 = Math.Sqrt(b1 + b2);
    return sqt1;
}
private double RectangleWidth(int w1, int w2, int w3, int w4, int w5, int w6, int w7, int w8)
{
    int a1 = w3 - w1;
    int a2 = w2 - w4;
    int b1 = a1 * a1;
    int b2 = a2 * a2;
    double sqt2 = Math.Sqrt(b1 + b2);
    return sqt2;
}

Upvotes: 0

Views: 3494

Answers (1)

ASh
ASh

Reputation: 35733

your computations of Width and Height are wrong. For rectangle it is simply Cx - Ax and Cy - Ay. also Top and Left are not equal to width and height:

SolidColorBrush partiallyTransparentSolidColorBrush = new SolidColorBrush(Colors.Green);
partiallyTransparentSolidColorBrush.Opacity = 0.25;

int ax = 146, ay = 557, cx = 1499, cy = 637;

var myRectangle = new Rectangle
{
    Height = cy - ay,
    Width = cx - ax,
    Fill = partiallyTransparentSolidColorBrush
};
Canvas.SetTop(myRectangle, ay);
Canvas.SetLeft(myRectangle, ax);
canvas.Children.Insert(0, myRectangle);

you can use Polygon instead of Rectangle and specify each point without doing any calculations:

var partiallyTransparentSolidColorBrush = new SolidColorBrush(Colors.Green);
partiallyTransparentSolidColorBrush.Opacity = 0.25;

var myRectangle = new Polygon
{
    //Stroke = Brushes.Black,
    //StrokeThickness = 2,
    Fill = partiallyTransparentSolidColorBrush,
    Points =
    {
        new Point(146, 557),
        new Point(1499, 557),
        new Point(1499, 637),
        new Point(146, 637),
    }
};

canvas.Children.Add(myRectangle);

using Polygon also allows to draw more complex shapes.

Upvotes: 1

Related Questions