UIImageView 图像纵横比在重新绘制以创建圆形蒙版后被弄乱了

UIImageView image aspect ratio is messed up after redrawing it to create a round mask

我的应用向 google 发送 GET 请求以获取某些用户信息。一条重要的返回数据是一张用户图片,它被放置在一个 UIImageView 中,该图片始终恰好为 (100, 100),然后重新绘制以为此 imageView 创建一个圆形遮罩。这些图片来自不同的来源,因此总是具有不同的纵横比。与高度相比,有些宽度更小,有时反之亦然。这导致图像看起来被压缩了。我已经尝试过以下方法(none 有效):

_personImage.layer.masksToBounds    = YES;
_personImage.layer.borderWidth      = 0;
_personImage.contentMode    = UIViewContentModeScaleAspectFit;
_personImage.clipsToBounds  = YES;

这是我用来重绘图像的代码(它是从用户 fnc12 获得的,作为 Making a UIImage to a circle form 中的第三个答案):

/** Returns a redrawn image that had a circular mask created for the inputted image. */
-(UIImage *)roundedRectImageFromImage:(UIImage *)image size:(CGSize)imageSize withCornerRadius:(float)cornerRadius
{
    UIGraphicsBeginImageContextWithOptions(imageSize, NO, 0.0);   //<== Notice 0.0 as third scale parameter. It is important because default draw scale ≠ 1.0. Try 1.0 - it will draw an ugly image...
    CGRect bounds       = (CGRect){CGPointZero, imageSize};
    [[UIBezierPath bezierPathWithRoundedRect:bounds cornerRadius:cornerRadius] addClip];
    [image drawInRect:bounds];
    UIImage *finalImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    return finalImage;
}

这个方法总是这样调用的:

[_personImage setImage:[self roundedRectImageFromImage:image size:CGSizeMake(_personImage.frame.size.width, _personImage.frame.size.height) withCornerRadius:_personImage.frame.size.width/2]];

所以我最终得到了一个完美的圆形图像,但它自己的图像在纵横比方面不正确。请帮忙。

P.S。以下是在重新绘制图像以创建圆形遮罩之前,当图像的宽度约为其高度的 70% 时图像的外观:

为了保持 UIImageView 的纵横比,在设置图像后使用下面的代码行。

[_personImage setContentMode:UIViewContentModeScaleAspectFill];

详细说明请参考link:
https://developer.apple.com/library/ios/documentation/UIKit/Reference/UIImageView_Class/

亲爱的朋友您好!

这是我的版本:

ViewController中的代码:

[self.profilePhotoImageView setContentMode:UIViewContentModeCenter];
[self.profilePhotoImageView setContentMode:UIViewContentModeScaleAspectFill];
[CALayer roundView:self.profilePhotoImageView];

我的 CALayer+Additions 中的 roundView 函数 class:

+(void)roundView:(UIView*)view{
    CALayer *viewLayer = view.layer;
    [viewLayer setCornerRadius:view.frame.size.width/2];
    [viewLayer setBorderWidth:0];
    [viewLayer setMasksToBounds:YES];
}

也许您应该尝试使用我通过修改 ImageView 的视图层 创建圆形 ImageView 的版本来改变创建圆形 ImageView 的方式。希望对你有帮助。