【问题标题】:how can I get the scale factor of a UIImageView who's mode is AspectFit?如何获得模式为 AspectFit 的 UIImageView 的比例因子?
【发布时间】:2011-10-07 06:32:45
【问题描述】:

如何获得模式为 AspectFit 的 UIImageView 的比例因子?

也就是说,我有一个模式为 AspectFit 的 UIImageView。图像(正方形)被缩放到我的 UIImageView 框架,这很好。

如果我想获得使用的比例尺(例如 0.78 或其他),我该如何直接获得?

我不想将父视图宽度与 UIImageView 宽度进行比较,因为计算必须考虑方向,注意我将方形图像缩放为矩形视图。因此,为什么我要直接查询 UIImageView 以找出答案。

编辑:我也需要它用于 iPhone 或 iPad 部署。

【问题讨论】:

  • 我终于计算出我需要的全部内容,而不是使用 UIImageView 和 aspectFit 内容模式。方便,就是丢失了很多细节信息。

标签: iphone ios uiview uiimageview


【解决方案1】:

你可以做类似的事情

CGFloat widthScale = imageView.image.size.width / imageView.frame.size.width;
CGFloat heightScale = imageView.image.size.height / imageView.frame.size.height;

让我知道这是否适合你。

【讨论】:

  • 谢谢,但我只关注整体比例因子(注意它是一个方面适合),我不想检测方向来查看方面适合是否会首先停止基于宽度或高度(如果您知道我的意思) - 正在寻找是否有办法在不查看帧大小和检测方向的情况下获取值..
【解决方案2】:

我为此编写了一个 UIImageView 类别:

UIImageView+ContentScale.h

#import <Foundation/Foundation.h>

@interface UIImageView (UIImageView_ContentScale)

-(CGFloat)contentScaleFactor;

@end

UIImageView+ContentScale.m

#import "UIImageView+ContentScale.h"

@implementation UIImageView (UIImageView_ContentScale)

-(CGFloat)contentScaleFactor
{
    CGFloat widthScale = self.bounds.size.width / self.image.size.width;
    CGFloat heightScale = self.bounds.size.height / self.image.size.height;

    if (self.contentMode == UIViewContentModeScaleToFill) {
        return (widthScale==heightScale) ? widthScale : NAN;
    }
    if (self.contentMode == UIViewContentModeScaleAspectFit) {
        return MIN(widthScale, heightScale);
    }
    if (self.contentMode == UIViewContentModeScaleAspectFill) {
        return MAX(widthScale, heightScale);
    }
    return 1.0;

}

@end

【讨论】:

  • 谢谢-顺便说一句“widthScale =”行,所以应该使用“self.bounds.size.width”而不是“self.frame.size.width”?
  • @greg 在大多数情况下没有区别。我在这里使用了边界,因为它与视图本身的大小有关。边界指定视图可以相对于自身绘制其内容的位置,框架指定相对于其父视图的位置。
  • 应该修复除零的情况
猜你喜欢
  • 1970-01-01
  • 2012-12-10
  • 1970-01-01
  • 2020-03-17
  • 1970-01-01
  • 2023-03-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多