How to round UIIMage with CGContext
How to round UIIMage with CGContext
func roundedRectImageFromImage(image:UIImage! ,radious:CGFloat) -> UIImage!{
if(radious == 0.0){
return image;
}
if( image != nil) {
let imageWidth:CGFloat = image.size.width;
let imageHeight:CGFloat = image.size.height;
let rect:CGRect = CGRectMake(0.0, 0.0, imageWidth, imageHeight);
let window:UIWindow = UIApplication.sharedApplication().windows[0]//[[[UIApplication sharedApplication] windows] objectAtIndex:0];
let scale:CGFloat = window.screen.scale;
UIGraphicsBeginImageContextWithOptions(rect.size,false, scale);
let context:CGContextRef = UIGraphicsGetCurrentContext()!;
CGContextBeginPath(context);
CGContextSaveGState(context);
CGContextTranslateCTM (context, CGRectGetMinX(rect), CGRectGetMinY(rect));
CGContextScaleCTM (context, radious, radious);
let rectWidth:CGFloat = CGRectGetWidth (rect)/radious;
let rectHeight:CGFloat = CGRectGetHeight (rect)/radious;
CGContextMoveToPoint(context, rectWidth, rectHeight/2.0);
CGContextAddArcToPoint(context, rectWidth, rectHeight, rectWidth/2.0, rectHeight, radious);
CGContextAddArcToPoint(context, 0.0, rectHeight, 0.0, rectHeight/2.0, radious);
CGContextAddArcToPoint(context, 0.0, 0.0, rectWidth/2.0, 0.0, radious);
CGContextAddArcToPoint(context, rectWidth, 0.0, rectWidth, rectHeight/2.0, radious);
CGContextRestoreGState(context);
CGContextClosePath(context);
CGContextClip(context);
image.drawInRect(CGRectMake(0.0, 0.0, imageWidth, imageHeight))
let newImage:UIImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return newImage;
}
return nil;
}
used:
let imageView = UIImageView(frame: CGRectMake(200,200,100,100));
imageView.image = roundedRectImageFromImage(UIImage(named: "name.jpg"),radious:6)
Comments
Post a Comment