4

ユーザーがランダムなCGPathを追加できるUIViewサブクラスがあります。CGPathは、UIPanGesturesを処理することによって追加されます。

UIViewのサイズをCGPathを含む可能な限り最小限に変更したいと思います。UIViewサブクラスでは、sizeThatFitsをオーバーライドして、最小サイズを次のように返します。

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

これは期待どおりに機能し、UIViewは返された値にサイズ変更されますが、CGPathも比例して「サイズ変更」され、ユーザーが最初に描画したものとは異なるパスになります。例として、これはユーザーが描いたパスのあるビューです。

描かれたパス

そして、これはサイズ変更後のパスを含むビューです。

ここに画像の説明を入力してください

パスを「サイズ変更」せずにUIViewのサイズを変更するにはどうすればよいですか?

4

1 に答える 1

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);
} 
于 2011-08-26T20:28:55.220 に答える