调整UIView大小以适合CGPath

Tom*_*omH 4 uiview cgpath ios

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

我想将UIView调整为包含CGPath的最小矩形.在我的UIView子类中,我重写了sizeThatFits以返回最小尺寸:

- (CGSize) sizeThatFits:(CGSize)size {
    CGRect box = CGPathGetBoundingBox(sigPath);
    return box.size;
}
Run Code Online (Sandbox Code Playgroud)

这按预期工作,并且UIView的大小调整为返回的值,但CGPath也按比例"调整大小",从而产生与用户最初绘制的路径不同的路径.例如,这是用户绘制的路径视图:

绘制的路径

这是调整大小后的路径视图:

在此输入图像描述

如何调整我的UIView大小而不是"调整"路径?

val*_*ine 6

使用CGPathGetBoundingBox.来自Apple文档:

返回包含图形路径中所有点的边界框.边界框是完全包围路径中所有点的最小矩形,包括Bézier和二次曲线的控制点.

这里有一个小概念验证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);
} 
Run Code Online (Sandbox Code Playgroud)