iphone - 多个 CGPoints 到 CGRect

标签 iphone objective-c cocoa-touch cocoa

我有一组 CGPoint 代表一个有点像倒“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);

编辑:我画了一些图片来展示我想要实现的目标。灰色区域显示 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/

相关文章:

iphone - Core Data : Post migration, 附加迁移代码

objective-c - 你如何在 Cocoa/Obj-C 中为 KVC 包装一个 BOOL?

objective-c - 仅将日期作为 NSDate 添加到核心数据中

iphone - 如何在iPhone上临时保存数据?

ios - 使用 AVCaptureVideoPreviewLayer 时如何保持捕获的视频大小

iphone - UITableview 的滚动改变了 UIButton 的图像,UITableview 滚动问题

iphone - 如何定义一个可以在我的应用程序的任何地方访问的全局变量?

iOS Key Value 观察Xcode项目问题

iOS - 核心数据集属性主键

ios - UIView渐进式动画