如何使用带有 aspectFill 和对齐到顶部的 UIImageView? [英] How can I use UIImageView with aspectFill and alignment to the top?

查看:41
本文介绍了如何使用带有 aspectFill 和对齐到顶部的 UIImageView?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何将 UIImageViewaspectFill 一起使用并对齐到顶部?自动布局或以编程方式不介意.

How could I use UIImageView with aspectFill and alignment to the top? Auto-layout or programmatically don't mind.

推荐答案

这是可以做到的,但是您谈论的编码相当多.让我们先详细说明您的要求.

我们将从纵向模式的 iPhone6s 开始,屏幕尺寸为 667x375 点,或按尺寸类别压缩宽度的常规高度.

We'll start with an iPhone6s in portrait mode with a screen size of 667x375 points, or a regular height by compressed width in size classes.

(请记住,在任何 iPad 上,您还需要使用滑盖和分屏.)

但现在我们将使用 667x375.我们将把我们的 imageView 添加为一个 375x375 的正方形.在纵向模式下沿着屏幕顶部.

But for now we'll go with 667x375. Into that we'll add our imageView as a square size of 375x375. Along the top of the screen when in portrait mode.

(请记住,使用 AutoLayout,您也将固定它,而无需输入一些代码来确定它是横向还是纵向,否则,如果下面有其他视图,375x375 将在横向上缩小它.)

现在,我们讨论了如何将图像"固定到大小为 375x375 且内容模式为 aspectFill 的 UIImageView 的顶部.

So now, stripped out to the most minimum (for now), we are talking about how to pin "an image" to the top of a UIImageView that is 375x375 in size and with a contentMode of aspectFill.

接下来我们需要找到图像的尺寸,根据最大尺寸(高度或宽度)以及该尺寸与 imageView 尺寸的比较,计算 imageView 通常如何渲染它.您想要的关键数字是它将呈现的高度

例如,如何将 480x1020 (HxW) 图像放入其中?1020 宽度将减少到 375,因此高度将为 480/(1020375) 或 176.4705 点.

For instance, how will a 480x1020 (HxW) image fit into it? The 1020 width will be taken down to 375, so the height will be 480/(1020375) or 176.4705 points.

始终对两个维度进行数学计算 - 如果您的 imageView 不是正方形或者如果高度不是有界"维度,您将被关闭.

Always do the math for both dimensions - if your imageView isn't square or if the height isn't the "bounded" dimension, you'll be off.

计算完Aspect Filled"高度后,根据 imageView 的尺寸检查它,并根据需要调整它的高度.

这里是真正的工作开始的地方.如果您正在使用 AutoLayout,您可以进行 heightAnchor 调整,但是根据您固定其他视图的方式,在您这样做之后,事情的布局可能会非常糟糕.如果您使用框架和 CGRects,请注意您必须考虑 iPad 滑出和分屏等.

Here's where the real work comes in. If you are using AutoLayout, you can do a heightAnchor adjustment, but depending on how you pinned those other views things may be laid out really bad after you do. If you are using frames and CGRects be aware that you have to take into account iPad slide-out and split screen, etc.

最后,如果您希望应用在加载后在该 imageView 中加载不同的图像,则必须将高度重置"回原来的高度,至少在您的计算中是这样.

我的建议是找到您所要求的替代方案.例如,在图像视图周围放置一个小边框,让用户知道该视图的真实尺寸.

My recommendation is to find an alternative to what you are asking. For instance, put a small border around the image view to let the user know the true dimensions of that view.

这篇关于如何使用带有 aspectFill 和对齐到顶部的 UIImageView?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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