2011-03-15 46 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