Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 991
erotsppa Avatar asked Jun 15 '09 14:06

erotsppa


People also ask

Which property is used to round the corners on an image?

The border-radius CSS property rounds the corners of an element's outer border edge. You can set a single radius to make circular corners, or two radii to make elliptical corners.


2 Answers

You can use CoreGraphics to create a path for a round rectangle with this code snippet:

static void addRoundedRectToPath(CGContextRef context, CGRect rect, float ovalWidth, float ovalHeight) {     float fw, fh;     if (ovalWidth == 0 || ovalHeight == 0) {         CGContextAddRect(context, rect);         return;     }     CGContextSaveGState(context);     CGContextTranslateCTM (context, CGRectGetMinX(rect), CGRectGetMinY(rect));     CGContextScaleCTM (context, ovalWidth, ovalHeight);     fw = CGRectGetWidth (rect) / ovalWidth;     fh = CGRectGetHeight (rect) / ovalHeight;     CGContextMoveToPoint(context, fw, fh/2);     CGContextAddArcToPoint(context, fw, fh, fw/2, fh, 1);     CGContextAddArcToPoint(context, 0, fh, 0, fh/2, 1);     CGContextAddArcToPoint(context, 0, 0, fw/2, 0, 1);     CGContextAddArcToPoint(context, fw, 0, fw, fh/2, 1);     CGContextClosePath(context);     CGContextRestoreGState(context); } 

And then call CGContextClip(context); to clip it to the rectangle path. Now any drawing done, including drawing an image, will be clipped to the round rectangle shape.

As an example, assuming "image" is a UIImage, and this is in a drawRect: method:

CGContextRef context = UIGraphicsGetCurrentContext(); CGContextSaveGState(context); addRoundedRectToPath(context, self.frame, 10, 10); CGContextClip(context); [image drawInRect:self.frame]; CGContextRestoreGState(context); 
like image 159
Ecton Avatar answered Sep 17 '22 10:09

Ecton


Here is an even easier method that is available in iPhone 3.0 and up. Every View-based object has an associated layer. Each layer can have a corner radius set, this will give you just what you want:

UIImageView * roundedView = [[UIImageView alloc] initWithImage: [UIImage imageNamed:@"wood.jpg"]]; // Get the Layer of any view CALayer * layer = [roundedView layer]; [layer setMasksToBounds:YES]; [layer setCornerRadius:10.0];  // You can even add a border [layer setBorderWidth:4.0]; [layer setBorderColor:[[UIColor blueColor] CGColor]]; 

To use these methods you might need to add:

#import <QuartzCore/QuartzCore.h> 
like image 26
MagicSeth Avatar answered Sep 20 '22 10:09

MagicSeth