调整UIView大小以适应CGPath

4

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

我想将UIView调整为包含CGPath的最小矩形大小。在我的UIView子类中,我已经重写了sizeThatFits以返回最小大小,如下所示:

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

这段代码可以按预期工作,UIView的大小会被调整到返回的值,但是CGPath也会按比例“调整”导致与用户最初绘制的路径不同。例如,这是用户绘制路径的视图:

Path as drawn

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

enter image description here

如何调整UIView的大小而不“调整”路径呢?

这里有一些问题。你找到解决方案了吗?谢谢! - valvoline
1个回答

6
使用CGPathGetBoundingBox。来自苹果文档:
返回包含图形路径中所有点的边界框。边界框是完全包围路径中所有点(包括贝塞尔和二次曲线的控制点)的最小矩形。
这里有一个小的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);
} 

1
不考虑行宽度 - jjxtra

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接