【问题标题】:How to get rectangle position by coordinate in wpf canvas如何通过wpf画布中的坐标获取矩形位置
【发布时间】:2018-09-07 21:54:07
【问题描述】:

我有一些用于绘制矩形的坐标。例如 A(146,557)、B(1499,557)、C(1499,637)、D(146,637)。

如何在 WPF 中使用坐标绘制矩形?

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);

这是我获取高度和宽度的方法。

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;
}

【问题讨论】:

    标签: c# .net wpf canvas


    【解决方案1】:

    您对宽度和高度的计算是错误的。对于矩形,它只是Cx - AxCy - Ay。 Top和Left也不等于宽度和高度:

    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);
    

    您可以使用 Polygon 代替 Rectangle 并指定每个点而不进行任何计算:

    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);
    

    使用多边形还可以绘制更复杂的形状。

    【讨论】:

    • 感谢您的回复,实际上,我正在获取此坐标形式的 OCR 名片扫描,我想通过使用 WPF 画布的 OCR 扫描仪坐标给出名片文本区域上的矩形。我必须使用多边形来创建矩形。使用多边形后得到结果link。请建议我这是在名片文本区域上获取矩形的正确方法。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-06-10
    • 2022-08-18
    • 2014-03-05
    • 2017-12-08
    • 1970-01-01
    • 2017-09-13
    • 2012-08-06
    相关资源
    最近更新 更多