如何调整UIImageView边界以剪切圆角UIImage?

时间:2016-08-12 15:38:44

标签: ios objective-c uiimageview uiimage uibezierpath

尝试根据另一个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"某种程度上来说?如果我可以按比例调整它,那就太好了。

还是其他任何更好的方法来实现这一目标?

1 个答案:

答案 0 :(得分:0)

感谢@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];

一个非常棘手的部分是“设置背景图像”还是仅设置UIButton的“设置图像”。后者在这里效果更好。设置背景图像似乎无法很好地处理图像的比例,但我相信有一种方法可以更好地完成它。在上面的例子中,设置图像更容易。