Cutting a square picture into a rounded picture in iOS is a very easy thing to do, setting imageview.layer directly. Cornerradius This property, and then set the ImageView. clipstobounds = YES, but for a picture of a rectangle it is not a rounded one, but an ellipse. To solve this problem, you need to draw and calculate. The end result is as follows:
Tips: If you are clipping a rectangle, it is clipped from the center of the picture.
The code is as follows:
@implementation UIImage (CF)
+ (UIImage*) Circleimagewith: (nsstring*) imageName borderWidth: (cgfloat) Width bordercolor: ( Uicolor*) color
{
UIImage* oldimage = [UIImage imagenamed: imageName];
cgfloat minLength = MIN(oldimage. Size. Width, oldimage. Size. Height);
cgfloat length = minLength + width * 2;
cgfloat centerx = length * 0.5;
cgfloat centery = length * 0.5;
cgfloat bigradius = length * 0.5;
uigraphicsbeginimagecontextwithoptions(cgsizemake(length, length), NO, 0.0 );
cgcontextref ctx = uigraphicsgetcurrentcontext();
// draw a great circle
[Color set];
Cgcontextaddarc(CTX, CenterX, CenterY, Bigradius, 0, m_pi * 2, 0);
Cgcontextfillpath(CTX);
// draw a small circle
cgfloat Smallradius = minLength * 0.5;
Cgcontextaddarc(CTX, CenterX, CenterY, Smallradius, 0, m_pi * 2, 0);
cgcontextclip(CTX);
cgfloat ImageX = centerx-oldimage. Size. Width * 0.5;
cgfloat imagey = centery-oldimage. Size. Height * 0.5;
[Oldimage drawinrect:cgrectmake(ImageX, Imagey, Oldimage. Size. Width, oldimage. Size. Height)];
UIImage* newimage = uigraphicsgetimagefromcurrentimagecontext();
Uigraphicsendimagecontext();
return newimage;
}
@end
iOS crop a rectangular picture into a circular picture