问题描述
我想使用宽高比选项将一个视图插入另一个视图.但是由于某些原因,我不能只设置contentMode
.
I want to insert one view into another with aspect fit option. But I can't just set contentMode
for some reasons.
您能否通过根据外部CGRect
调整内部CGRect
的大小来提供解决方案?
Could you provide a solution via resizing of the inner CGRect
according to the outer CGRect
?
是的,有很多类似的问题,但是没有人提供这样的解决方案.
And yes, there are a lot of similar questions but no one provides such solution.
推荐答案
我写了一个应该可以实现您想要的功能的函数.
在缩放比例使其适合给定outerRect
的同时,它会返回给定innerRect
的CGRect
,同时保持宽高比. innerRect
将位于outerRect
的中心.
I wrote a function that should achieve what you desire.
It will return the CGRect
of a given innerRect
, after scaling it to fit within a given outerRect
, while maintaining aspect ratio. The innerRect
will be centered within the 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
而言太宽,因此将根据其宽度进行缩放.
In this case, the innerRect
is too wide for the outerRect
, so it will be scaled according to it's width.
在这里,红色区域是innerRect
,绿色区域是outerRect
.最初它们的高度相同,但是按比例缩小(宽度是原来的2倍) ),现在innerRect
的高度是outerRect
的一半.
Here, the red area is the innerRect
and the green area is the outerRect
. They both originally had the same height, but after being scaled down (as it was 2x as wide), the innerRect
now has half the height of the outerRect
.
此处,innerRect
作为子视图添加到了outerRect
. 如果要将它们添加到同一超级视图中,可以将outerRect
的frame
传递给函数,而不是bounds
.
Here the innerRect
is added as a subview to the outerRect
. If you want to add them to the same superview, you can pass the outerRect
's frame
into the function, rather than the bounds
.
这篇关于方面是否可以通过编程以适应iOS?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!