Turn two CGPoints into a CGRect

▼魔方 西西 提交于 2019-12-03 09:20:40

问题


How can I, given two different CGPoints, turn them into an CGRect?

Example:

CGPoint p1 = CGPointMake(0,10);
CGPoint p2 = CGPointMake(10,0);

How can I turn this into a CGRect?


回答1:


This will take two arbitrary points and give you the CGRect that has them as opposite corners.

CGRect r = CGRectMake(MIN(p1.x, p2.x), 
                      MIN(p1.y, p2.y), 
                      fabs(p1.x - p2.x), 
                      fabs(p1.y - p2.y));

The smaller x value paired with the smaller y value will always be the origin of the rect (first two arguments). The absolute value of the difference between x values will be the width, and between y values the height.




回答2:


A slight modification of Ken's answer. Let CGGeometry "standardize" the rect for you.

CGRect rect = CGRectStandardize(CGRectMake(p1.x, p1.y, p2.x - p1.x, p2.y - p1.y));




回答3:


Assuming p1 is the origin and the other point is the opposite corner of a rectangle, you could do this:

CGRect rect = CGRectMake(p1.x, p1.y,  fabs(p2.x-p1.x), fabs(p2.y-p1.y));



回答4:


This function takes any number of CGPoints and gives you the smallest CGRect back.

CGRect CGRectSmallestWithCGPoints(CGPoint pointsArray[], int numberOfPoints)
{
    CGFloat greatestXValue = pointsArray[0].x;
    CGFloat greatestYValue = pointsArray[0].y;
    CGFloat smallestXValue = pointsArray[0].x;
    CGFloat smallestYValue = pointsArray[0].y;

    for(int i = 1; i < numberOfPoints; i++)
    {
        CGPoint point = pointsArray[i];
        greatestXValue = MAX(greatestXValue, point.x);
        greatestYValue = MAX(greatestYValue, point.y);
        smallestXValue = MIN(smallestXValue, point.x);
        smallestYValue = MIN(smallestYValue, point.y);
    }

    CGRect rect;
    rect.origin = CGPointMake(smallestXValue, smallestYValue);
    rect.size.width = greatestXValue - smallestXValue;
    rect.size.height = greatestYValue - smallestYValue;

    return rect;
}



回答5:


This will return a rect of width or height 0 if the two points are on a line

float x,y,h,w;
if (p1.x > p2.x) {
    x = p2.x;
    w = p1.x-p2.x;
} else {
    x = p1.x;
    w = p2.x-p1.x;
}
if (p1.y > p2.y) {
    y = p2.y;
    h = p1.y-p2.y;
} else {
    y = p1.y;
    h = p2.y-p1.y;
}

CGRect newRect = CGRectMake(x,y,w,h);



回答6:


Swift extension:

extension CGRect {
    init(p1: CGPoint, p2: CGPoint) {
        self.init(x: min(p1.x, p2.x),
                  y: min(p1.y, p2.y),
                  width: abs(p1.x - p2.x),
                  height: abs(p1.y - p2.y))
    }
}


来源:https://stackoverflow.com/questions/8100845/turn-two-cgpoints-into-a-cgrect

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!