How to get the size of a scaled UIImage in UIImageView?(如何在 UIImageView 中获取缩放的 UIImage 的大小?)
问题描述
UIImageView
的image.size
属性给出了原始UIImage
的大小.我想知道将自动缩放图像放入 UIImageView
时的大小(通常小于原始图像).
The image.size
attribute of UIImageView
gives the size of the original UIImage
. I would like to find out the size of the autoscaled image when it is put in the UIImageView
(typically smaller than the original).
例如,我将图像设置为 Aspect Fit
.现在我想知道它在屏幕上的新高度和宽度,以便在新缩放的图像上准确地绘制.
For example, I have the image set to Aspect Fit
. Now I want to know its new height and width on the screen so I can draw accurately on the new scaled image.
有没有什么方法可以做到这一点,而无需自己根据 UIImageView 的大小来解决?UIImage 原始大小(基本上是对其缩放进行逆向工程)?
Is there any way to do this without figuring it out myself based on the UIImageView size & UIImage original size (basically reverse engineering its scaling)?
推荐答案
Objective-C:
-(CGRect)frameForImage:(UIImage*)image inImageViewAspectFit:(UIImageView*)imageView
{
float imageRatio = image.size.width / image.size.height;
float viewRatio = imageView.frame.size.width / imageView.frame.size.height;
if(imageRatio < viewRatio)
{
float scale = imageView.frame.size.height / image.size.height;
float width = scale * image.size.width;
float topLeftX = (imageView.frame.size.width - width) * 0.5;
return CGRectMake(topLeftX, 0, width, imageView.frame.size.height);
}
else
{
float scale = imageView.frame.size.width / image.size.width;
float height = scale * image.size.height;
float topLeftY = (imageView.frame.size.height - height) * 0.5;
return CGRectMake(0, topLeftY, imageView.frame.size.width, height);
}
}
斯威夫特 4:
func frame(for image: UIImage, inImageViewAspectFit imageView: UIImageView) -> CGRect {
let imageRatio = (image.size.width / image.size.height)
let viewRatio = imageView.frame.size.width / imageView.frame.size.height
if imageRatio < viewRatio {
let scale = imageView.frame.size.height / image.size.height
let width = scale * image.size.width
let topLeftX = (imageView.frame.size.width - width) * 0.5
return CGRect(x: topLeftX, y: 0, width: width, height: imageView.frame.size.height)
} else {
let scale = imageView.frame.size.width / image.size.width
let height = scale * image.size.height
let topLeftY = (imageView.frame.size.height - height) * 0.5
return CGRect(x: 0.0, y: topLeftY, width: imageView.frame.size.width, height: height)
}
}
这篇关于如何在 UIImageView 中获取缩放的 UIImage 的大小?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何在 UIImageView 中获取缩放的 UIImage 的大小?
基础教程推荐
- 在 gmail 中为 ios 应用程序检索朋友的朋友 2022-01-01
- 如何在没有IB的情况下将2个按钮添加到右侧的UINavigationbar? 2022-01-01
- android 应用程序已发布,但在 google play 中找不到 2022-01-01
- 如何让对象对 Cocos2D 中的触摸做出反应? 2022-01-01
- UIWebView 委托方法 shouldStartLoadWithRequest:在 WKWebView 中等效? 2022-01-01
- 当从同一个组件调用时,两个 IBAction 触发的顺序是什么? 2022-01-01
- 如何在 iPhone 上显示来自 API 的 HTML 文本? 2022-01-01
- Kivy Buildozer 无法构建 apk,命令失败:./distribute.sh -m “kivy"d 2022-01-01
- 如何在 UIImageView 中异步加载图像? 2022-01-01
- Android:对话框关闭而不调用关闭 2022-01-01