简体   繁体   中英

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

Try to get a rounded UIImage based on another UIImageView:

1) The UIImageView to be referred:

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

2) Round the UIImage:

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

3) How to round the 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;
}

Problem:

I want to clip a UIImage (not UIImageView) to be a rounded one. However, the rounded UIImage I got now is bigger than I want.

Should I resize the "imageView.bounds" in some way? It will be great if I can just resize it proportionally.

Or any other better way to achieve that?

Thanks to @brandonscript, I finally figured out a way to do this.

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];

A very tricky part is whether to "set the background image" or just "set image" of the UIButton. The latter works better here. Setting the background image seems not to be able to handle the scale of the image well, though I believe there is a way to better do it. Setting the image is easier in the case above.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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