iOS crop a rectangular picture into a circular picture

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.