@@ -68,29 +68,69 @@ - (UIImage *)imageByScaleAndCrop:(CGSize)targetSize {
6868}
6969
7070- (UIImage *)imageByCircularScaleAndCrop : (CGSize)targetSize {
71+ // bitmap context properties
72+ float scaleFactor = [[UIScreen mainScreen ] scale ];
7173
72- // Create the bitmap graphics context
73- UIGraphicsBeginImageContextWithOptions (targetSize, NO , 0.0 );
74+ CGColorSpaceRef colorSpace =
75+ CGColorSpaceCreateDeviceRGB ();
76+ CGContextRef context =
77+ CGBitmapContextCreate (NULL ,
78+ targetSize.width * scaleFactor,
79+ targetSize.height * scaleFactor,
80+ 8 ,
81+ targetSize.width * scaleFactor * 4 ,
82+ colorSpace,
83+ kCGImageAlphaPremultipliedFirst );
84+
85+ CGContextScaleCTM (context,
86+ scaleFactor,
87+ scaleFactor);
88+
89+ CGContextBeginPath (context);
90+
91+ CGContextAddArc (context,
92+ targetSize.width / 2 ,
93+ targetSize.height / 2 ,
94+ targetSize.width / 2 ,
95+ 0 ,
96+ 2 * M_PI ,
97+ 0 );
98+
99+ CGContextClosePath (context);
100+
101+ CGFloat widthFactor = targetSize.width / self.size .width ;
102+ CGFloat heightFactor = targetSize.height / self.size .height ;
103+
104+ if (widthFactor > heightFactor) {
105+ scaleFactor = widthFactor;
106+ }
107+ else {
108+
109+ scaleFactor = heightFactor;
110+ }
111+
112+ float w = self.size .width * scaleFactor;
113+ float h = self.size .height * scaleFactor;
74114
75- CGContextRef context = UIGraphicsGetCurrentContext ();
76- // Create and CLIP to a CIRCULAR Path
77- // (This could be replaced with any closed path if you want a different shaped clip)
78- CGContextBeginPath (context);
79- CGContextAddArc (context, targetSize.width / 2 , targetSize.height / 2 , targetSize.width / 2 , 0 , 2 * M_PI , 0 );
80- CGContextClosePath (context);
81115 CGContextClip (context);
82- // Set the SCALE factor for the graphics context
83- // All future draw calls will be scaled by this factor
84- CGContextScaleCTM (context, targetSize.width / self.size .width , targetSize.height / self.size .height );
85- // Draw the IMAGE
86- CGRect myRect = CGRectMake (0 , 0 , self.size .width , self.size .height );
87- [self drawInRect: myRect];
116+ // draw image into bitmap context
117+ CGContextDrawImage (context,
118+ CGRectMake (0 ,0 , w, h),
119+ self.CGImage );
88120
89- UIImage *circularImage = UIGraphicsGetImageFromCurrentImageContext ();
121+ CGImageRef renderedImage =
122+ CGBitmapContextCreateImage (context);
90123
91- UIGraphicsEndImageContext ();
124+ // tidy up
125+ CGColorSpaceRelease (colorSpace);
126+ CGContextRelease (context);
127+
128+ UIImage *image =
129+ [UIImage imageWithCGImage: renderedImage
130+ scale: 0
131+ orientation: self .imageOrientation];
92132
93- return circularImage ;
133+ return image ;
94134}
95135
96136@end
0 commit comments