UIImage with smooth rounded corners in quartz

青春壹個敷衍的年華 提交于 2019-12-17 20:27:50

问题


I am just testing the following code to round corners on UIImage:

- (UIImage *)makeRoundedImage:(UIImage *)image radius:(float)radius;
{
    CALayer *imageLayer = [CALayer layer];
    imageLayer.frame = CGRectMake(0, 0, image.size.width, image.size.height);
    imageLayer.contents = (id) image.CGImage;

    imageLayer.masksToBounds = YES;
    imageLayer.cornerRadius = radius;

    UIGraphicsBeginImageContext(image.size);
    [imageLayer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage *roundedImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    return roundedImage;
}

I looks fine unless you look closely to generated image. Corners are not smooth. How can I make corners to be smoother/softer ?

EDIT:

Processed image with rounded corners in quartz:

Like you can see corner is not smooth.

This is version with UIImageView's cornerRadius that is much more smoother.

Where is the catch ?


回答1:


Here is UIImage category:

- (UIImage *) imageWithRoundedCornersRadius: (float) radius
{
    // Begin a new image that will be the new image with the rounded corners
    UIGraphicsBeginImageContextWithOptions(self.size, NO, 0);

    // Add a clip before drawing anything, in the shape of an rounded rect
    CGRect rect = CGRectMake(0, 0, self.size.width, self.size.height);
    [[UIBezierPath bezierPathWithRoundedRect:rect cornerRadius:radius] addClip];

    // Draw your image
    [self drawInRect:rect];

    // Get the image, here setting the UIImageView image
    UIImage *roundedImage = UIGraphicsGetImageFromCurrentImageContext();

    // Lets forget about that we were drawing
    UIGraphicsEndImageContext();

    return roundedImage;
}


来源:https://stackoverflow.com/questions/14071278/uiimage-with-smooth-rounded-corners-in-quartz

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!