Redimensionner UIView pour l'adapter à un CGPath

J'ai une sous-class UIView sur laquelle l'user peut append un CGPath random. Le CGPath est ajouté en traitant UIPanGestures.

Je voudrais resize l'UIView au rectangle minimal possible qui contient le CGPath. Dans ma sous-class UIView, j'ai remplacé sizeThatFits pour returnner la taille minimale en tant que telle:

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

Cela fonctionne comme prévu et l'UIView est redimensionné à la valeur renvoyée, mais le CGPath est également «redimensionné» proportionnellement résultant dans un path différent de ce que l'user avait dessiné à l'origine. A titre d'exemple, c'est la vue avec un path tracé par l'user:

Chemin tracé

Et voici la vue avec le path après le redimensionnement:

entrez la description de l'image ici

Comment puis-je resize mon UIView et ne pas "resize" le path?

Utilisez le CGPathGetBoundingBox. De la documentation Apple:

Renvoie la boîte englobante contenant tous les points d'un tracé graphique. La boîte englobante est le plus petit rectangle englobant complètement tous les points du path, y compris les points de contrôle pour les courbes de Bézier et les courbes quadratiques.

Voici une petite démonstration des methods drawRect. J'espère que cela vous aide!

 - (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); }