如何调整 UIImageView 边界的大小以裁剪圆形的 UIImage?

How to Resize UIImageView Bounds in order to Clip a Rounded UIImage?

尝试获取基于另一个 UIImageView 的圆形 UIImage:

1)要引用的UIImageView:

@interface CompetitorAnalysisViewController ()
@property (weak, nonatomic) IBOutlet UIImageView *submitImageButton;
@end

2) 对UIImage进行四舍五入:

UIImage *chosenImage = info[UIImagePickerControllerEditedImage];
// Round the image
UIImage *roundedChosenImage = [self getRoundedRectImageFromImage:chosenImage onReferenceView:_submitImageButton withCornerRadius: _submitImageButton.frame.size.width/2];

3) 如何对UIImage进行四舍五入:

- (UIImage *)getRoundedRectImageFromImage :(UIImage *)image onReferenceView :(UIImageView*)imageView withCornerRadius :(float)cornerRadius
{
    UIGraphicsBeginImageContextWithOptions(imageView.bounds.size, NO, 0);
    [[UIBezierPath bezierPathWithRoundedRect:imageView.bounds
                            cornerRadius:cornerRadius] addClip];
    [image drawInRect:imageView.bounds];
    UIImage *finalImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    return finalImage;
}

问题:

我想将 UIImage(不是 UIImageView)裁剪成圆形。但是,我现在得到的圆形UIImage比我想要的要大。

我应该以某种方式调整 "imageView.bounds" 的大小吗?如果我能按比例调整它就太好了。

或者任何其他更好的方法来实现它?

感谢@brandonscript,我终于想出了办法。

UIImage *chosenImage = info[UIImagePickerControllerEditedImage];

// Create a reference ImageView
UIImageView *referenceImageView =[[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 135, 135)];
// Round the image
UIImage *roundedChosenImage = [self getRoundedRectImageFromImage:chosenImage onReferenceView:referenceImageView withCornerRadius: referenceImageView.frame.size.width/2];

[choosePhotoButton setImage:roundedChosenImage forState:UIControlStateNormal];
[picker dismissViewControllerAnimated:YES completion:NULL];

一个非常棘手的部分是 "set the background image" 还是只是 "set image" 的 UIButton。后者在这里效果更好。设置背景图像似乎无法很好地处理图像的比例,但我相信有一种方法可以更好地做到这一点。在上面的例子中设置图像更容易。