在iOS中以编程方式拟合?

Vya*_*cov 4 objective-c rect ios cgrect aspect-fit

我想使用方面适合选项将一个视图插入到另一个视图中。但是contentMode由于某些原因我不能设置。

您能否通过CGRect根据外部调整内部大小来提供解决方案CGRect

是的,有很多类似的问题,但没有人提供这样的解决方案。

Ham*_*ish 5

我写了一个应该实现你想要的功能。

它将返回CGRect给定的innerRect,在将其缩放以适应给定的 之后outerRect,同时保持纵横比。在innerRect将内居中outerRect

static inline CGRect aspectFitRect(CGRect outerRect, CGRect innerRect) {

    // the width and height ratios of the rects
    CGFloat wRatio = outerRect.size.width/innerRect.size.width;
    CGFloat hRatio = outerRect.size.height/innerRect.size.height;

    // calculate scaling ratio based on the smallest ratio.
    CGFloat ratio = (wRatio < hRatio)? wRatio:hRatio;

    // The x-offset of the inner rect as it gets centered
    CGFloat xOffset = (outerRect.size.width-(innerRect.size.width*ratio))*0.5;

    // The y-offset of the inner rect as it gets centered
    CGFloat yOffset = (outerRect.size.height-(innerRect.size.height*ratio))*0.5;

    // aspect fitted origin and size
    CGPoint innerRectOrigin = {xOffset+outerRect.origin.x, yOffset+outerRect.origin.y};
    CGSize innerRectSize = {innerRect.size.width*ratio, innerRect.size.height*ratio};

    return (CGRect){innerRectOrigin, innerRectSize};
}
Run Code Online (Sandbox Code Playgroud)

然后你可以像这样使用它:

// outer rect
CGRect outerRect = CGRectMake(0, 100, self.view.bounds.size.width, 500);

// outer rect's view
UIView* v = [[UIView alloc] initWithFrame:outerRect];
v.backgroundColor = [UIColor greenColor];
[self.view addSubview:v];

// inner rect
CGRect innerRect = CGRectMake(0, 0, self.view.bounds.size.width*2, 500);
CGRect scaledInnerRect = aspectFitRect(v.bounds, innerRect);

// inner rect's view
UIView* v1 = [[UIView alloc] initWithFrame:scaledInnerRect];
v1.backgroundColor = [UIColor redColor];
[v addSubview:v1];
Run Code Online (Sandbox Code Playgroud)

在这种情况下, 对innerRect来说太宽了outerRect,所以它会根据它的宽度进行缩放。

在此处输入图片说明

这里,红色区域是innerRect,绿色区域是outerRect它们最初具有相同的高度,但在按比例缩小后(因为它是 2 倍宽),innerRect现在的高度是outerRect.

这里innerRect将作为子视图添加到outerRect. 如果要将它们添加到同一个超级视图中,可以将outerRect's传递frame到函数中,而不是将bounds.