How to mask a square image into an image with round corners in iOS?

前端 未结 8 1681
[愿得一人]
[愿得一人] 2020-11-28 01:20

How can you mask a square image into an image with round corners?

8条回答
  •  渐次进展
    2020-11-28 02:01

    Building off of algal, here are a couple methods that are nice to put in an UIImage category:

    
    - (UIImage *) roundedCornerImageWithRadius:(CGFloat)radius
    {
        CGRect imageRect = CGRectMake(0, 0, self.size.width, self.size.height);
        UIGraphicsBeginImageContextWithOptions(imageRect.size,NO,0.0); //scale 0 yields better results
    
        //create a bezier path defining rounded corners and use it for clippping
        UIBezierPath * path = [UIBezierPath bezierPathWithRoundedRect:imageRect cornerRadius:radius];
        [path addClip];
    
        // draw the image into the implicit context
        [self drawInRect:imageRect];
    
        // get image and cleanup
        UIImage *roundedCornerImage = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
        return roundedCornerImage;
    }
    
    + (UIImage *)imageWithColor:(UIColor *)color size:(CGSize)size andCornerRadius:(CGFloat)radius
    {
        UIImage *image = nil;
        if (size.width == 0 || size.height == 0) {
            size = CGSizeMake(1.0, 1.0);
        }
        CGRect rect = CGRectMake(0.0f, 0.0f, size.width, size.height);
        UIGraphicsBeginImageContextWithOptions(rect.size,NO,0.0); //yields sharper results than UIGraphicsBeginImageContext(rect.size)
        CGContextRef context = UIGraphicsGetCurrentContext();
        if (context)
        {
            CGContextSetFillColorWithColor(context, [color CGColor]);
            if (radius > 0.0) {
                //create a bezier path defining rounded corners and use it for clippping
                UIBezierPath * path = [UIBezierPath bezierPathWithRoundedRect:rect cornerRadius:radius];
                [path addClip];
                CGContextAddPath(context, path.CGPath);
            }
            CGContextFillRect(context, rect);
            image = UIGraphicsGetImageFromCurrentImageContext();
            UIGraphicsEndImageContext();
        }
        return image;
    }
    

提交回复
热议问题