调整UIView大小以适合CGPath

时间:2011-03-15 20:06:17

标签: ios uiview cgpath

我有一个UIView子类,用户可以在其上添加随机CGPath。通过处理UIPanGestures添加CGPath。

我想将UIView调整为包含CGPath的最小矩形。在我的UIView子类中,我重写了sizeThatFits以返回最小尺寸:

- (CGSize) sizeThatFits:(CGSize)size {
    CGRect box = CGPathGetBoundingBox(sigPath);
    return box.size;
}

这可以按预期工作,并且UIView的大小调整为返回的值,但CGPath也按比例“调整大小”,从而产生与用户最初绘制的路径不同的路径。例如,这是具有用户绘制的路径的视图:

Path as drawn

这是调整大小后路径的视图:

enter image description here

如何调整我的UIView大小而不是“调整”路径?

1 个答案:

答案 0 :(得分:6)

使用CGPathGetBoundingBox。来自Apple文档:

  

返回包含图形路径中所有点的边界框。该   边界框是完全包围所有点的最小矩形   在路径中,包括Bézier和二次曲线的控制点。

这里有一个小概念验证drawRect方法。希望它能帮到你!

- (void)drawRect:(CGRect)rect {

    //Get the CGContext from this view
    CGContextRef context = UIGraphicsGetCurrentContext();

    //Clear context rect
    CGContextClearRect(context, rect);

    //Set the stroke (pen) color
    CGContextSetStrokeColorWithColor(context, [UIColor blackColor].CGColor);

    //Set the width of the pen mark
    CGContextSetLineWidth(context, 1.0);

    CGPoint startPoint = CGPointMake(50, 50);
    CGPoint arrowPoint = CGPointMake(60, 110);

    //Start at this point
    CGContextMoveToPoint(context, startPoint.x, startPoint.y);
    CGContextAddLineToPoint(context, startPoint.x+100, startPoint.y);
    CGContextAddLineToPoint(context, startPoint.x+100, startPoint.y+90);
    CGContextAddLineToPoint(context, startPoint.x+50, startPoint.y+90);
    CGContextAddLineToPoint(context, arrowPoint.x, arrowPoint.y);
    CGContextAddLineToPoint(context, startPoint.x+40, startPoint.y+90);
    CGContextAddLineToPoint(context, startPoint.x, startPoint.y+90);
    CGContextAddLineToPoint(context, startPoint.x, startPoint.y);

    //Draw it
    //CGContextStrokePath(context);

    CGPathRef aPathRef = CGContextCopyPath(context);

    // Close the path
    CGContextClosePath(context);

    CGRect boundingBox = CGPathGetBoundingBox(aPathRef);
    NSLog(@"your minimal enclosing rect: %.2f %.2f %.2f %.2f", boundingBox.origin.x, boundingBox.origin.y, boundingBox.size.width, boundingBox.size.height);
}