将UIImage转换为圆形形式

38

我一直在尝试将UIImage裁剪成一个圆形。 我现在使用的是在其他答案中很流行的代码,但是尽管我得到了一个圆形,它的边缘非常锯齿状而不是平滑的。 有人可以帮忙吗?我怎样才能得到一个完美、平滑的圆形?

我用来创建遮罩的代码是:

  (UIImage*) maskImage:(UIImage *)image withMask:(UIImage *)maskImage {

    CGImageRef imageNoAlpha = image.CGImage;

    CGColorSpaceRef cs = CGColorSpaceCreateDeviceRGB();

    CGFloat width = CGImageGetWidth(imageNoAlpha);
    CGFloat height = CGImageGetWidth(imageNoAlpha);

    CGContextRef ctxWithAlpha = CGBitmapContextCreate(nil, width, height, 8, 4*width, cs, kCGImageAlphaPremultipliedFirst);

    CGContextDrawImage(ctxWithAlpha, CGRectMake(0, 0, width, height), imageNoAlpha);

    CGImageRef imageWithAlpha = CGBitmapContextCreateImage(ctxWithAlpha);

    CGImageRef maskRef = maskImage.CGImage; 

    CGImageRef mask = CGImageMaskCreate(CGImageGetWidth(maskRef),
                                        CGImageGetHeight(maskRef),
                                        CGImageGetBitsPerComponent(maskRef),
                                        CGImageGetBitsPerPixel(maskRef),
                                        CGImageGetBytesPerRow(maskRef),
                                        CGImageGetDataProvider(maskRef), NULL, false);

    CGImageRef masked = CGImageCreateWithMask(imageWithAlpha, mask);

    UIImage* retImage= [UIImage imageWithCGImage:masked];
    UIImage* retImageFixed = [retImage transparentBorderImage:1];

    CGImageRelease(mask);
    CGImageRelease(masked);
    CGImageRelease(imageWithAlpha);
    CGContextRelease(ctxWithAlpha);
    CGColorSpaceRelease(cs);

    return retImageFixed;

提前致谢...


可能会有帮助,以下两个链接或许是你所寻找的。1. https://dev59.com/M2855IYBdhLWcg3wUSgW 2. https://dev59.com/9XI-5IYBdhLWcg3wZ3UR - iOS
谢谢。我看到很多人说你可以只使用圆角半径属性,但那是错误的。虽然它确实使角落变圆,但它永远不会使整个图像看起来像一个圆形。 - Shahar Nechmad
10个回答

50

尝试使用这段代码

yourImageView.layer.cornerRadius = yourImageView.frame.size.height /2;
yourImageView.layer.masksToBounds = YES;
yourImageView.layer.borderWidth = 0;

这个展示的图片类似于iOS 7圆形图片,谢谢。


1
请注意,这个解决方案会使表视图的滚动变得缓慢。@aToz的解决方案运行良好。 - xiaowl
4
它在tableView滚动中工作得非常完美,我没有发现任何问题,我的tableView包含246行,每一行都从服务器加载图像,但仍然能够完美运行。 - aLFaRSi
@aLFaRSi,你使用的是什么类型的设备?性能不佳的代码并不总是一开始就表现出来。可以有一个理论证明或基准测试两种方法。 - scord
@alFaRSi。你很幸运 ;) - Jeff
这里使用了 UIImageView,而主题发起者要求的是一个圆形遮罩的 UIImage - hotdogsoup.nl

28

这可能会对你有所帮助,将参考视图的一半作为圆角传递,以便在想要显示图像的位置上显示图像,或者您可以设置自定义矩形,

例如,在我的情况下,我想在一个"imageView"上显示图像,因此在这种情况下,圆角将为imageView.frame.size.width/2

- (void)displayImage
{
    imageView.image = [self getRoundedRectImageFromImage:@"Test.png" onReferenceView:imageView withCornerRadius: imageView.frame.size.width/2];
}



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

    return finalImage;
}

8
在UIGraphicsBeginImageContextWithOptions函数中,第三个参数必须是0.0而不是1.0。因为1.0会画出非常难看的图像。 - fnc12
4
@fnc12 谢谢!我想知道为什么结果模糊难看。 - Chen Li Yong

17

抱歉格式不美观。 aToz答案的更好版本。

@interface UIImage (CircleMask)

+ (UIImage *)roundedRectImageFromImage :(UIImage *)image
                                  size :(CGSize)imageSize
                      withCornerRadius :(float)cornerRadius;

@end

@implementation UIImage(CircleMask)

+(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 cause 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;
}

@end

用Swift实现相同的功能:

extension UIImage{

    class func roundedRectImageFromImage(image:UIImage,imageSize:CGSize,cornerRadius:CGFloat)->UIImage{
        UIGraphicsBeginImageContextWithOptions(imageSize, false, 0.0)
        let bounds = CGRect(origin: CGPointZero, size: imageSize)
        UIBezierPath(roundedRect: bounds, cornerRadius: cornerRadius).addClip()
        image.drawInRect(bounds)
        let finalImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return finalImage
    }
    
}

1
CGPointZero已经被弃用,请使用CGRect(origin: .zero, size: imageSize)代替。 - grebulon

15

对aToz和fnc12答案的改进版(使用Swift语言):

extension UIImage
{
    func roundImage() -> UIImage
    {
        let newImage = self.copy() as! UIImage
        let cornerRadius = self.size.height/2
        UIGraphicsBeginImageContextWithOptions(self.size, false, 1.0)
        let bounds = CGRect(origin: CGPointZero, size: self.size)
        UIBezierPath(roundedRect: bounds, cornerRadius: cornerRadius).addClip()
        newImage.drawInRect(bounds)
        let finalImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return finalImage
    }
}

使用方法:

self.userImageView.image = image.roundedImage()

非正方形的图片能否进行裁剪和圆角处理? - khunshan

3

我觉得我应该加入这个讨论。以下是一个有效且紧凑的Swift 5解决方案:

extension UIImage {

    var rounded: UIImage? {
        UIGraphicsBeginImageContextWithOptions(size, false, UIScreen.main.scale)
        defer { UIGraphicsEndImageContext() }
        let bounds = CGRect(origin: .zero, size: size)
        UIBezierPath(roundedRect: bounds, cornerRadius: size.height/2.0).addClip()
        draw(in: bounds)
        return UIGraphicsGetImageFromCurrentImageContext()
    }

}


1

从UIImageView获取帮助怎么样?

+ (UIImage *)circularImage:(UIImage *)image withDiameter:(NSUInteger)diameter
{
    CGRect frame = CGRectMake(0.0f, 0.0f, diameter, diameter);
    UIImageView *imageView = [[UIImageView alloc] initWithFrame:frame];
    imageView.contentMode = UIViewContentModeScaleAspectFill;
    imageView.clipsToBounds = YES;
    imageView.image = image;
    CALayer *layer = imageView.layer;


    layer.masksToBounds = YES;

    layer.cornerRadius =MAX( imageView.frame.size.height,imageView.frame.size.width)/2;

    UIGraphicsBeginImageContextWithOptions(imageView.bounds.size,NO, [UIScreen mainScreen].scale);
    CGContextRef context = UIGraphicsGetCurrentContext();
    [layer renderInContext:context];


    UIImage *roundedImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    return roundedImage;
}

1
如果你正在使用Swift,可以导入'AlamofireImage'并使用其中一个函数。对于圆形图像:
let roundImage = UIImage(named: "myImage")!.af_imageRoundedIntoCircle()

0
如果您正在使用UIImageView并且希望在保持圆角的同时动画显示图像的大小,可以应用以下转换:

Objective-C

// Our UIImageView reference
@property (weak, nonatomic) IBOutlet UIImageView *myImageView;

- (void)viewDidLoad {
    [super viewDidLoad];

     myImageView.layer.cornerRadius = myImageView.frame.size.width / 2.0f;
     myImageView.transform = CGAffineTransformScale(CGAffineTransformIdentity, 0.4f, 0.4f);
}

- (void)viewDidAppear:(BOOL)animated {
    [UIView animateWithDuration:1.0 animations:^{
        myImageView.transform = CGAffineTransformIdentity;
    }];
}

Swift

// Our UIImageView reference
@IBOutlet weak var myImageView:UIImageView!

override func viewDidLoad() {
    super.viewDidLoad()

    myImageView.layer.cornerRadius = myImageView.frame.size.width / 2;
    myImageView.transform = CGAffineTransformScale(CGAffineTransformIdentity, 0.4, 0.4)
}

override func viewDidAppear(animated: Bool) {
    UIView.animateWithDuration(1.0) {
        myImageView.transform = CGAffineTransformIdentity;
    }
}

注意:这也将保持任何自动布局约束条件


-1

试一下这个

UIImageView *circleImageview=[[UIImageView alloc]init];
circleImageview.frame=CGRectMake(0,10, 80, 80)]; 
circleImageview.layer.cornerRadius=circleimagview.frame.size.height/2;
 circleImageview.userInteractionEnabled=YES;
 [self.view addSubview:circleImageview];

注意:确保该视图的高度和宽度相同。

-1
我用UIBezierPath解决了我的问题。
UIBezierPath *path = [UIBezierPath bezierPathWithOvalInRect:yourImageView.bounds];
CAShapeLayer *maskLayer = [CAShapeLayer layer];
maskLayer.path = path.CGPath;
yourImageView.layer.mask = maskLayer;

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接