简体   繁体   English

ImageView contentMode以正确缩放图像?

[英]ImageView contentMode to scale images properly?

I'm drawing a bunch of UIImageView (100x100) as menu items. 我正在绘制一堆UIImageView(100x100)作为菜单项。 Each has its own image, some are larger than 100x100, some smaller. 每个都有自己的图像,有些大于100x100,有些较小。 By default, the imageViews with larger images are being scaled down in ratio to fit the 100x100 box nicely. 默认情况下,具有较大图像的imageViews将按比例缩小以很好地适合100x100框。

However, images smaller than 100x100 are being scaled up, which makes them really blurry. 但是,小于100x100的图像正在按比例放大,这使它们真正变得模糊。 I'd like it so the smaller images simply remain the size they naturally are. 我想要这样,以便较小的图像仅保持其自然大小。 Otherwise I'm happy with the way large images are scaling, just not the smaller images. 否则,我会对大型图像缩放的方式感到满意,而对较小的图像则不满意。

I haven't been able to achieve anything by switching to UIViewContentModeScaleAspectFit , UIViewContentModeScaleAspectFill , or UIViewContentModeScaleToFill . 我无法通过切换到UIViewContentModeScaleAspectFitUIViewContentModeScaleAspectFillUIViewContentModeScaleToFill来实现任何目的。

Does anyone have ideas or hacks on how I could achieve this? 是否有人对我如何实现这一目标有想法或技巧? I could use an if statement to check the image's dimensions and sent their contentMode (Center?), but that seems a bit hackish since I'm drawing each item from an NSDictionary with a for in loop. 我可以使用if语句来检查图像的尺寸并发送它们的contentMode(Center?),但这似乎有点骇人听闻,因为我是使用for in循环从NSDictionary绘制每个项目的。 Any help appreciated. 任何帮助表示赞赏。 Thanks 谢谢

If I understand correctly you can just check the image dimensions first before setting your frame, something like: 如果我理解正确,则可以在设置框架之前先检查图像尺寸,例如:

UIImageView *imageView = [[UIImageView alloc] initWithImage:[UIImage imageName:@"myimage.png"]];
[imageView sizeToFit];

CGRect newFrame = imageView.frame;
if (newFrame.size.width > 100) newFrame.size.width = 100;
imageView.frame = newFrame;

You'll need some extra logic to do similar things for the height. 您需要一些额外的逻辑来对高度进行类似的操作。 Is this what you mean? 你是这个意思吗?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM