You need to make a transparent UIView (background color alpha of 0), and then, in its drawRect:, draw your circle using CoreGraphics calls. You could also edit the view's layer, and give it a cornerRadius.
Enter Swift as Language and choose Storyboard as User Interface, Choose Next. Select File -> New File -> iOS -> Cocoa Touch Class. Name the class CircleView with a subclass of UIView. This class will contain the views where the circles will be drawn.
You could use QuartzCore and do something this --
self.circleView = [[UIView alloc] initWithFrame:CGRectMake(10,20,100,100)];
self.circleView.alpha = 0.5;
self.circleView.layer.cornerRadius = 50; // half the width/height
self.circleView.backgroundColor = [UIColor blueColor];
Would I just override the drawRect method?
Yes:
- (void)drawRect:(CGRect)rect
{
CGContextRef ctx = UIGraphicsGetCurrentContext();
CGContextAddEllipseInRect(ctx, rect);
CGContextSetFillColor(ctx, CGColorGetComponents([[UIColor blueColor] CGColor]));
CGContextFillPath(ctx);
}
Also, would it be okay to change the frame of that view within the class itself?
Ideally not, but you could.
Or do I need to change the frame from a different class?
I'd let the parent control that.
Here is another way by using UIBezierPath (maybe it's too late ^^) Create a circle and mask UIView with it, as follows:
UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 200, 200)];
view.backgroundColor = [UIColor blueColor];
CAShapeLayer *shape = [CAShapeLayer layer];
UIBezierPath *path = [UIBezierPath bezierPathWithArcCenter:view.center radius:(view.bounds.size.width / 2) startAngle:0 endAngle:(2 * M_PI) clockwise:YES];
shape.path = path.CGPath;
view.layer.mask = shape;
My contribution with a Swift extension:
extension UIView {
func asCircle() {
self.layer.cornerRadius = self.frame.width / 2;
self.layer.masksToBounds = true
}
}
Just call myView.asCircle()
Swift 3 - custom class, easy to reuse. It uses backgroundColor
set in UI builder
import UIKit
@IBDesignable
class CircleBackgroundView: UIView {
override func layoutSubviews() {
super.layoutSubviews()
layer.cornerRadius = bounds.size.width / 2
layer.masksToBounds = true
}
}
Swift 3 class:
import UIKit
class CircleView: UIView {
override func draw(_ rect: CGRect) {
guard let context = UIGraphicsGetCurrentContext() else {return}
context.addEllipse(in: rect)
context.setFillColor(UIColor.blue.cgColor)
context.fillPath()
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With