简体   繁体   English

如何修剪UIImageView以适合长宽比图像

[英]How can I trim a UIImageView to fit an aspect ratio image

I am using a crop tool in my app and I need to modify a UIImageView so that it fits an image exactly after inserting the image in aspect fit mode. 我在应用程序中使用了裁剪工具,我需要修改UIImageView,以使其在以宽高比模式插入图像后恰好适合图像。

So an image is selected and added to the UIImageView in aspect fit mode. 因此,将在宽高比适合模式下选择图像并将其添加到UIImageView。 The problem is that this then leaves "blank space" around the image inside the UIImageView that needs trimming. 问题在于,这会在需要修剪的UIImageView内的图像周围留下“空白”。 I was wondering how I could then go and resize the holding UIImageView based upon the image inside. 我想知道如何然后根据内部图像来调整持有的UIImageView的大小。

Is this possible? 这可能吗?

The Easy way is simply using the following code on your "imageView" 简单的方法就是在“ imageView”上使用以下代码

imageView.contentMode = UIViewContentModeScaleAspectFit;

Assuming you want to cut a "zoomed" section of your image to fit fully into your imageView 假设您要剪切图像的“缩放”部分以完全适合您的imageView

  1. check your original image width and height 检查原始图像的宽度和高度
  2. Assuming width is bigger in size then height , scale the image width to the holder width 假设宽度的大小大于高度,则将图像宽度缩放到支架宽度
  3. center the image on your holder , the width will fit perfectly (section2) and the height will simply be cropped follow above and below the holder. 将图像居中放置在支架上,宽度将完全适合(第2节),高度将根据支架的上方和下方进行裁剪。

It turns out that a better approach is to use the following idea. 事实证明,更好的方法是使用以下想法。

How to get the size of a scaled UIImage in UIImageView? 如何在UIImageView中获取缩放后的UIImage的大小?

Instead of trimming the UIImageView, insert the image and then get the dimensions of the image inside the UIImageView, from there you can then resize the UIImageView to match the dimensions of the image inside. 无需修剪UIImageView,而是插入图像,然后在UIImageView内获取图像的尺寸,然后可以从此处调整UIImageView的大小以匹配内部图像的尺寸。

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

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