2011-03-15 5 views
4

사용자가 임의 CGPath를 추가 할 수있는 UIView 하위 클래스가 있습니다. CGPath는 UIPanGestures를 처리하여 추가됩니다.CGPath에 맞게 UIView 크기 조정

나는 CGPath를 포함하는 가능한 최소 rect로 UIView의 크기를 조정하고 싶습니다. 내 UIView의 서브 클래스에서, 나는 같은 최소한의 크기를 반환하는 sizeThatFits을 재정의 :

예상하고있는 UIView 값의 크기를 조정할 반환하지만, CGPath는 "크기 조정"있는 그대로이 작동
- (CGSize) sizeThatFits:(CGSize)size { 
    CGRect box = CGPathGetBoundingBox(sigPath); 
    return box.size; 
} 

비례 A의 결과 사용자가 원래 그렸던 것과 다른 경로. 예를 들어,이 사용자에 의해 그려진 같은 경로로 볼 수 있습니다 :

Path as drawn

는 그리고이 크기 조정 후 경로로 볼 수 있습니다 :

enter image description here

내가 크기를 조정할 수있는 방법 내 UIView 및 ""크기를 조정하지?

+0

일부 문제는 여기에 있습니다. 해결책을 찾았습니까? 감사! – valvoline

답변

6

CGPathGetBoundingBox를 사용하십시오. Apple 설명서에서

그래픽 경로의 모든 점을 포함하는 경계 상자를 반환합니다. 경계 상자는 베 지어 및 2 차 곡선의 제어점을 포함하여 경로의 모든 점 을 완전히 둘러싸는 가장 작은 직사각형입니다.

여기에 작은 개념 증명 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

관련 문제