调整UIView以适应CGPath

我有一个UIView子类,用户可以在其中添加一个随机的CGPath。 CGPath是通过处理UIPanGestures添加的。

我想将UIView调整到包含CGPath的最小矩形。 在我的UIView子类中,我重载了sizeThatFits来返回最小尺寸,如下所示:

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

这可以按预期工作,并且UIView被调整为返回的值,但是CGPath也是按比例“resize”,导致与用户最初绘制的path不同。 作为一个例子,这是用户绘制的path的视图:

路径如图所示

这是resize后的path:

在这里输入图像说明

我怎样才能调整我的UIView,而不是“调整”的path?

使用CGPathGetBoundingBox。 从Apple文档:

返回包含graphicspath中所有点的边界框。 边界框是完全封闭path中所有点的最小矩形,包括Bézier和二次曲线的控制点。

这里有一个小概念validation的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); }