我想使用宽高比匹配选项将一个 View 插入到另一个 View 中。但由于某些原因,我不能只设置 contentMode
。
您能否提供一个根据外部 CGRect
调整内部 CGRect
大小的解决方案?
是的,有很多类似的问题,但没有人提供这样的解决方案。
最佳答案
我编写了一个应该可以实现您想要的功能的函数。
它将返回给定 innerRect
的 CGRect
,在缩放它以适合给定 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};
}
然后您可以像这样使用它:
// 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];
在本例中,innerRect
对于 outerRect
来说太宽,因此它将根据其宽度进行缩放。
这里,红色区域是innerRect
,绿色区域是outerRect
。它们最初具有相同的高度,但是之后缩小(因为宽度是原来的 2 倍),innerRect
现在的高度是 outerRect
的一半。
此处,innerRect
作为 subview 添加到 outerRect
中。 如果您想将它们添加到同一个 super View 中,您可以将 outerRect
的 frame
传递到函数中,而不是 bounds
>.
关于ios - 在 iOS 中以编程方式适配方面?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35507331/