如何获得模式为 AspectFit 的 UIImageView 的比例因子? [英] how can I get the scale factor of a UIImageView who's mode is AspectFit?

查看:17
本文介绍了如何获得模式为 AspectFit 的 UIImageView 的比例因子?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

how can I get the scale factor of a UIImageView who's mode is AspectFit?

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

That is, I have a UIImageView with mode AspectFit. The image (square) is scaled to my UIImageView frame which is fine.

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

If I want to get the amount of scale that was used (e.g. 0.78 or whatever) how can I get this directly?

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

I don't want to have to compare say a parent view width to the UIImageView width as the calculation would have to take into account orientation, noting I'm scaling a square image into a rectangular view. Hence why I was after a direct way to query the UIImageView to find out.

我需要它也适用于 iPhone 或 iPad 部署.

I need it to work for iPhone or iPad deployment as well.

推荐答案

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

I've written a UIImageView category for that:

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

这篇关于如何获得模式为 AspectFit 的 UIImageView 的比例因子?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆