Search code examples
apache-flexrect

Calculate centre point of rectangle in flex


I have two rectangles:

var rect1:Rectangle = new Rectangle(66,147,89,67);

var rect2:Rectangle = new Rectangle(155,147,89,67);

How to calculate the centre point of these rectangles based on their x and y positions. I want the centre point to be calculated with relative to stage


Solution

  • In Global Way. First you need to find the minimum and maximum points of your shapes in this case rectangles. Than you need to use min.x+(max.x-min.x)/2 and min.y+(max.y-min.y)/2

    here is code how to do that.

    var rects:Array={rectangle1,rectangle2}
    var min:Point=new Point(Number.MAX_VALUE,NUMBER.MAX_VALUE)
    var max:Point=new Point(Number.MIN_VALUE,NUMBER.MIN_VALUE)
    foreach(var rect:rectangle in rects)
    {
        min.x=Math.min(min.x,rect.left);
        min.y=Math.min(min.y,rect.top);
        max.x=Math.max(max.x,rect.right);
        max.y=Math.max(max.y,rect.bottom);
    }
    

    var center:Point=new Point(min.x+(max.x-min.x)/2,min.y+(max.y-min.y)/2) if your rectangles are in another container rather than stage you can call contaner.localToGLobal(center) the result is point that is position relative to stage