Resize UIView to match CGPath

I have a subclass of UIView on which the user can add random CGPath. CGPath is added by UIPanGestures processing.

I would like to resize the UIView to the smallest possible that contains CGPath. In my UIView subclass, I overridden sizeThatFits to return the minimum size as such:

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

This works as expected, and the UIView will be changed to the return value, but CGPath will also be β€œchanged” proportionally, which will lead to another path that was originally made by the user. As an example, this is a view showing the path drawn by the user:

Path as drawn

And this is the outline view after resizing:

enter image description here

How to resize UIView instead of resizing path?

+4
source share
1 answer

Use the CGPathGetBoundingBox. From the Apple documentation:

Returns a bounding box containing all the points in the graphics path. A bounding box is the smallest rectangle that spans all points on the path, including control points for Beziers and quadratic curves.

Here are some small drawRescription drawing methods. Hope this helps you!

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

Source: https://habr.com/ru/post/1343838/


All Articles