本文介绍了调整UIView的大小以适合CGPath的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

我想将UIView调整为包含CGPath的最小可能。在我的UIView子类中,我重写了sizeThatFits以返回最小大小:

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

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

这按预期工作,UIView的大小调整为返回的值,但是CGPath也按比例调整大小,导致用户最初绘制的路径不同。例如,这是一个用户绘制的路径视图:

This works as expected and the UIView is resized to the value returned, but the CGPath is also "resized" proportionally resulting in a different path that what the user had originally drawn. As an example, this is the view with a path as drawn by the user:

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

And this is the view with the path after resizing:

我该怎么办?调整我的UIView大小而不是调整路径?

How can I resize my UIView and not "resize" the path?

推荐答案

使用CGPathGetBoundingBox。来自Apple文档:

Use the CGPathGetBoundingBox. From Apple documentation:

这里有一个小概念验证drawRect方法。希望它对你有帮助!

Here a small proof-of-concept drawRect methods. Hope it 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);
}

这篇关于调整UIView的大小以适合CGPath的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-31 03:12