ios - 在 iOS 中以编程方式适配方面?

标签 ios objective-c cgrect rect aspect-fit

我想使用宽高比匹配选项将一个 View 插入到另一个 View 中。但由于某些原因,我不能只设置 contentMode

您能否提供一个根据外部 CGRect 调整内部 CGRect 大小的解决方案?

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

最佳答案

我编写了一个应该可以实现您想要的功能的函数。

它将返回给定 innerRectCGRect,在缩放它以适合给定 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 来说太宽,因此它将根据其宽度进行缩放。

enter image description here

这里,红色区域是innerRect,绿色区域是outerRect它们最初具有相同的高度,但是之后缩小(因为宽度是原来的 2 倍),innerRect 现在的高度是 outerRect 的一半。

此处,innerRect 作为 subview 添加到 outerRect 中。 如果您想将它们添加到同一个 super View 中,您可以将 outerRectframe 传递到函数中,而不是 bounds >.

关于ios - 在 iOS 中以编程方式适配方面?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35507331/

相关文章:

ios - 如何以编程方式快速向 UITableViewCell 内的 UIStackView 添加约束?

objective-c - 自定义 NSCell drawWithFrame :inView method not getting invoked in OSX 10. 8

swift - 将自定义 CGRect 函数从 Objective-C 转换为 Swift 时遇到问题

ios - UIImageView 未在 iOS 中显示

ios - 用户在 iOS 上关闭应用程序后执行操作

ios - Metal API 验证崩溃

objective-c - 将 NSDate 的 NSArray 转换为格式化日期字符串数组

ios - 无法将 parentContext 添加到 NSManagedObjectContext,上下文已经有一个协调器

ios - 如何在 UIImageView 的屏幕上获得绝对矩形

crash - 获取 CGRect View