UIImage with transparent rounded corners

后端 未结 5 2080
无人共我
无人共我 2020-12-03 15:50

I\'m using following code to add rounded corners to my UIImage, but the problem is that the rounded corners are showing \"white\" area instead of transparent or \"clear\". W

相关标签:
5条回答
  • 2020-12-03 16:41

    https://github.com/detroit-labs/AmazeKit

    sounds like a job for a library

    0 讨论(0)
  • 2020-12-03 16:46

    Here's a simpler formulation using UIKit calls:

    - (UIImage*) roundCorneredImage: (UIImage*) orig radius:(CGFloat) r {
        UIGraphicsBeginImageContextWithOptions(orig.size, NO, 0);
        [[UIBezierPath bezierPathWithRoundedRect:(CGRect){CGPointZero, orig.size} 
                                    cornerRadius:r] addClip];
        [orig drawInRect:(CGRect){CGPointZero, orig.size}];
        UIImage* result = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
        return result;
    }
    

    Notice the NO parameter - this makes the image context transparent, so the clipped-out region is transparent.

    0 讨论(0)
  • 2020-12-03 16:46
    profileImageView.layer.cornerRadius = profileImageView.frame.size.height/2;
    profileImageView.clipsToBounds = YES;
    
    0 讨论(0)
  • 2020-12-03 16:52

    Right after creating the bitmap context clear it with:

    CGContextClearRect (context, CGRectMake(0, 0, w, h));
    
    0 讨论(0)
  • 2020-12-03 16:53

    lukya's comment below your question is what you probably want to do.

    Make sure you import QuartzCore:

    #import <QuartzCore/QuartzCore.h>
    

    Then, if you have a UIImageView of your image that you want to have rounded corners, just call (assuming imageView is a property and cornerRadius is the desired corner radius):

    self.imageView.layer.cornerRadius = cornerRadius;
    self.imageView.clipsToBounds = YES;
    

    Since you already have self.CGImage, you could do this to create a UIImageView:

    UIImageView *imageView = [[UIImageView alloc] initWithImage:[UIImage imageWithCGImage:self.CGImage]];
    

    Just make sure to release the imageView after you add it as a subview.

    0 讨论(0)
提交回复
热议问题