Cut a UIImage into a circle:
Cut a UIImage into a circle
suggest changeObjective-C version
The code in the viewDidLoad or loadView:
import #include <math.h>
- (void)loadView
{
[super loadView];
UIImageView *imageView=[[UIImageView alloc]initWithFrame:CGRectMake(0, 50, 320, 320)];
[self.view addSubview:imageView];
UIImage *image=[UIImage imageNamed:@"Dubai-Photos-Images-Travel-Tourist-Images-Pictures-800x600.jpg"];
imageView.image=[self circularScaleAndCropImage:[UIImage imageNamed:@"Dubai-Photos-Images-Travel-Tourist-Images-Pictures-800x600.jpg"] frame:CGRectMake(0, 0, 320, 320)];
}
Finally the function which does the heavy lifting circularScaleAndCropImage is as defined below
- (UIImage*)circularScaleAndCropImage:(UIImage*)image frame:(CGRect)frame {
// This function returns a newImage, based on image, that has been:
// - scaled to fit in (CGRect) rect
// - and cropped within a circle of radius: rectWidth/2
// Create the bitmap graphics context
UIGraphicsBeginImageContextWithOptions(CGSizeMake(frame.size.width, frame.size.height), NO, 0.0);
CGContextRef context = UIGraphicsGetCurrentContext();
// Get the width and heights
CGFloat imageWidth = image.size.width;
CGFloat imageHeight = image.size.height;
CGFloat rectWidth = frame.size.width;
CGFloat rectHeight = frame.size.height;
// Calculate the scale factor
CGFloat scaleFactorX = rectWidth/imageWidth;
CGFloat scaleFactorY = rectHeight/imageHeight;
// Calculate the centre of the circle
CGFloat imageCentreX = rectWidth/2;
CGFloat imageCentreY = rectHeight/2;
// Create and CLIP to a CIRCULAR Path
// (This could be replaced with any closed path if you want a different shaped clip)
CGFloat radius = rectWidth/2;
CGContextBeginPath (context);
CGContextAddArc (context, imageCentreX, imageCentreY, radius, 0, 2*M_PI, 0);
CGContextClosePath (context);
CGContextClip (context);
// Set the SCALE factor for the graphics context
// All future draw calls will be scaled by this factor
CGContextScaleCTM (context, scaleFactorX, scaleFactorY);
// Draw the IMAGE
CGRect myRect = CGRectMake(0, 0, imageWidth, imageHeight);
[image drawInRect:myRect];
UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return newImage;
}
SWIFT 3 Example
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
let imageView = UIImageView(frame: CGRect(x: CGFloat(0), y: CGFloat(50), width: CGFloat(320), height: CGFloat(320)))
view.addSubview(imageView)
let image = UIImage(named: "Dubai-Photos-Images-Travel-Tourist-Images-Pictures-800x600.jpg")
imageView.image = circularScaleAndCropImage(UIImage(named: "Dubai-Photos-Images-Travel-Tourist-Images-Pictures-800x600.jpg")!, frame: CGRect(x: CGFloat(0), y: CGFloat(0), width: CGFloat(100), height: CGFloat(100)))
}
Finally the function which does the heavy lifting circularScaleAndCropImage is as defined below
func circularScaleAndCropImage(_ image: UIImage, frame: CGRect) -> UIImage{
// This function returns a newImage, based on image, that has been:
// - scaled to fit in (CGRect) rect
// - and cropped within a circle of radius: rectWidth/2
//Create the bitmap graphics context
UIGraphicsBeginImageContextWithOptions(CGSize(width: CGFloat(frame.size.width), height: CGFloat(frame.size.height)), false, 0.0)
let context: CGContext? = UIGraphicsGetCurrentContext()
//Get the width and heights
let imageWidth: CGFloat = image.size.width
let imageHeight: CGFloat = image.size.height
let rectWidth: CGFloat = frame.size.width
let rectHeight: CGFloat = frame.size.height
//Calculate the scale factor
let scaleFactorX: CGFloat = rectWidth / imageWidth
let scaleFactorY: CGFloat = rectHeight / imageHeight
//Calculate the centre of the circle
let imageCentreX: CGFloat = rectWidth / 2
let imageCentreY: CGFloat = rectHeight / 2
// Create and CLIP to a CIRCULAR Path
// (This could be replaced with any closed path if you want a different shaped clip)
let radius: CGFloat = rectWidth / 2
context?.beginPath()
context?.addArc(center: CGPoint(x: imageCentreX, y: imageCentreY), radius: radius, startAngle: CGFloat(0), endAngle: CGFloat(2 * Float.pi), clockwise: false)
context?.closePath()
context?.clip()
//Set the SCALE factor for the graphics context
//All future draw calls will be scaled by this factor
context?.scaleBy(x: scaleFactorX, y: scaleFactorY)
// Draw the IMAGE
let myRect = CGRect(x: CGFloat(0), y: CGFloat(0), width: imageWidth, height: imageHeight)
image.draw(in: myRect)
let newImage: UIImage? = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return newImage!
}
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents
1
UILabel
5
UIButton
10
UITableView
11
Auto Layout
12
UIView
14
MKMapView
15
UIColor
17
CAAnimation
18
UITextView
20
Concurrency
25
UIStackView
26
UIImage
27
UIWebView
28
CALayer
30
NSDate
31
Custom Fonts
34
UIScrollView
35
Localization
37
UITextField
40
iBeacon
41
CLLocation
42
NSURLSession
43
UISwitch
47
PDF Creation
49
NSTimer
50
CGContext
55
FacebookSDK
56
AFNetworking
57
CTCallCenter
61
UIBezierPath
63
UIAppearance
67
Storyboard
69
Fastlane
70
CAShapeLayer
71
WKWebView
73
Categories
77
UIPickerView
78
Dynamic Type
79
NSURL
86
IBOutlets
87
AWS SDK
91
UIDevice
92
CloudKit
93
GameplayKit
96
NSData
98
Deep Linking
100
Core Graphics
101
Segues
102
UIDatePicker
103
NSPredicate
104
EventKit
105
NSBundle
106
SiriKit
110
NSURLConnection
111
StoreKit
112
Code signing
114
Resizing UIImage
117
3D Touch
119
Keychain
122
Block
123
Content Hugging
125
Navigation Bar
129
Cut a UIImage into a circle
136
Graph Coreplot
138
FCM Messaging
140
Custom Keyboard
141
AirDrop
144
UISlider
145
Carthage
146
HealthKit
147
Core SpotLight
148
UI Testing
149
Core Motion
150
QR Code Scanner
151
plist
152
NSInvocation
155
AppDelegate
157
MVVM
158
UIStoryboard
161
MPVolumeView
164
UIPhoenix
166
Simulator
167
BackgroundModes
168
NSArray
169
OpenGL
172
MVP Architecture
173
UIKit Dynamics
175
Core Data
179
MyLayout
180
UIFont
181
Simulator Builds
189
Security
195
UITableViewCell
200
Codable
201
FileHandle
202
NSUserActivity
210
Contributors