2011-03-15 47 views
4

我有一个UIView子类,用户可以在其中添加一个随机CGPath。 CGPath是通过处理UIPanGestures添加的。调整UIView以适合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,而不是“调整”的路径?

+0

这里有一些问题。你找到了解决方案吗?谢谢! – valvoline

回答

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); 
} 
+0

不考虑线宽 – jjxtra