CGRect的多个CGPoints

JWo*_*ood 3 iphone cocoa cocoa-touch objective-c

我有一组CGPoints代表一个有点像倒置'T'形状的形状,现在我想将这些点转换成CGRect适合形状的一个,所以创建一个CGRect包含整个形状的我只是循环通过并计算最低点xy左上角,最高点xy右下角这是很好的但是在图像外留下白色区域,我怎么能找出没有白色区域的最大矩形,所以最终的形状更像是一个'|' 形状?我的代码到目前为止:

CGPoint topLeft = CGPointZero;
CGPoint bottomRight = CGPointZero;
for( NSValue *value in points ) {
    CGPoint point = [value CGPointValue];
    if( topLeft.x == 0 || topLeft.x > point.x ) shapeRect.x = point.x;
    if( topLeft.y == 0 || topLeft.y > point.y ) shapeRect.y = point.y;
    if( bottomRight.x < point.x ) bottomRight.x = point.x;
    if( bottomRight.y < point.y ) bottomRight.y = point.y;
}
CGRect shapeRect = CGRectMake(topLeft.x, topLeft.y, bottomRight.x - topLeft.x, bottomRight.y - topLeft.y);
Run Code Online (Sandbox Code Playgroud)

编辑:我画了一些照片来展示我想要实现的目标.灰色区域显示CGRect.

这是图像形状,我有形状中每个点的坐标:

图片由ImageShack.us提供http://img684.imageshack.us/img684/121/crop1.png

这是我上面的代码产生的:

图片由ImageShack.us主持http://img26.imageshack.us/img26/2521/crop2j.png

这是我想要实现的目标:

图片由ImageShack.us提供http://img689.imageshack.us/img689/5499/crop3.png

hfo*_*sli 5

难以掌握你实际要问的内容.关于标题,此函数将为任意数量的CGPoints创建最小的rect.

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;
}
Run Code Online (Sandbox Code Playgroud)

可以像这样使用

CGPoint poinstArray[] = {topLeft, bottomRight};
CGRect smallestRect = CGRectSmallestWithCGPoints(poinstArray, 2);
Run Code Online (Sandbox Code Playgroud)