简体   繁体   English

裁剪UIImage以适合帧图像

[英]Crop UIImage to fit a frame image

I need to crop a UIImage , taken with the device camera, so that it fits inside another UIImage , which represents a frame (with rounded borders and so on). 我需要裁剪UIImage ,使用设备相机拍摄,以便它适合另一个UIImage ,它代表一个frame (带有圆形边框等)。 Check the image below: 检查下图:

在此输入图像描述 Using Aspect Fill 使用Aspect Fill

在此输入图像描述 Using Aspect Fit 使用Aspect Fit

So, what I need is to remove the image excess that is out of the frame bounds. 所以,我需要的是删除超出帧边界的图像多余。 I tried using UIBezierPath , CGImageRef and other methods that I Googled but I'm not finding a solution for this. 我尝试使用UIBezierPathCGImageRef和我用Google搜索的其他方法,但我没有找到解决方案。

In Interface Builder, use the following configuration: 在Interface Builder中,使用以下配置:

在此输入图像描述

There are two important settings, namely: 有两个重要的设置,即:

  1. Mode: Aspect Fill

  2. Clip Subviews

It can also be done programmatically: 它也可以通过编程方式完成:

[imageView setContentMode:UIViewContentModeScaleAspectFill];
[imageView setClipsToBounds:YES];

This will correctly fill the view with the image, keep its aspect ratio and hide what doesn't fit. 这将正确地用图像填充视图,保持其纵横比并隐藏不适合的内容。

make a IBOutlet in your controller. 在控制器中创建一个IBOutlet

@property (retain)IBOutlet UIImageView* imageView;

and in -(void) viewDidLoad set -(void) viewDidLoad设置

imageView.layer.masksToBounds = YES;

In interface Builder, access the Mode menu inside of the detail pane (the fourth one) and choose the right one for your UIImageView (I guess "center" or "aspect fit"). 在界面生成器中,访问详细信息窗格(第四个)中的“ 模式”菜单,然后为UIImageView选择正确的菜单(我猜“中心”或“纵横比”)。

在此输入图像描述

OLD ANSWER: 老答案:

You can use the contentGravity property of CALayer to make it work 您可以使用CALayer的contentGravity属性使其工作

A constant that specifies how the layer's contents are positioned or scaled within its bounds. 一个常量,指定图层的内容在其边界内的定位或缩放方式。

  @property(copy) NSString *contentsGravity 

使用UIImageView并执行

imageView.contentMode = UIViewContentModeScaleAspectFit;

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

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