我有一组 CGPoint
代表一个有点像倒“T”形的形状,现在我想将这些点转换成一个 CGRect
适合形状内部,因此要创建一个包含整个形状的 CGRect
,我只是循环遍历并计算出最低的 x
和 y
对于左上角和右下角最高的 x
和 y
这很好但是在图像之外留下了白色区域,我怎么能找出没有白色的最大矩形所以最终的形状更像是一个“|”形状?到目前为止我的代码:
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);
编辑:我画了一些图片来展示我想要实现的目标。灰色区域显示 CGRect
。
这是图像形状,我有形状中每个点的坐标:
Image Hosted by ImageShack.us http://img684.imageshack.us/img684/121/crop1.png
这是我上面的代码产生的结果:
Image Hosted by ImageShack.us http://img26.imageshack.us/img26/2521/crop2j.png
这是我要实现的目标:
Image Hosted by ImageShack.us http://img689.imageshack.us/img689/5499/crop3.png
最佳答案
很难掌握您实际询问的内容。关于标题,此函数将为任意数量的 CGPoint 创建最小的矩形。
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;
}
可以这样使用
CGPoint poinstArray[] = {topLeft, bottomRight};
CGRect smallestRect = CGRectSmallestWithCGPoints(poinstArray, 2);
关于iphone - 多个 CGPoints 到 CGRect,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8795170/