Sometimes you might want to create a Circle out of a UIView or want to create an static Circle on the view or subview or on a map which always stays at the center because there is no way you can keep the provided Circle class (Google Maps) of a map always at the center.
Let’s see how to do that.
Create a new project and drag a Slider on the controller, create it’s action of type UISlider and set its Minimum and Maximum value to 30 and 200 respectively(or whatever you like).
Create two variables
1 2 |
let circleView = UIView() var sliderCurrentValue : CGFloat! |
and write the following function in your ViewController.
1 2 3 4 5 6 7 8 9 10 11 12 13 |
func circularView(x : CGFloat, y : CGFloat , radius : CGFloat ){ circleView.frame = CGRectMake(x, y , radius, radius) self.circleView.layer.borderColor = UIColor(red: 247.0/255, green: 159.0/255, blue: 50.0/255, alpha: 1.0).CGColor self.circleView.layer.borderWidth = 3; circleView.backgroundColor = UIColor(red: 158.0/255, green: 220.0/255, blue: 247.0/255, alpha: 0.5) view.addSubview(circleView) view.bringSubviewToFront(circleView) self.circleView.layer.cornerRadius = CGRectGetWidth(self.circleView.frame)/2 self.circleView.clipsToBounds = true circleView.userInteractionEnabled = false; } |
After that in your viewDidLoad() call your function.
1 2 3 4 |
override func viewDidLoad() { super.viewDidLoad() circularView(view.center.x - 30/2, y: view.center.y - 30/2, radius: 30) } |
After that in your Slider Action
1 2 3 4 5 |
@IBAction func sliderAction(sender: UISlider) { sliderCurrentValue = CGFloat(sender.value) circularView(view.center.x - sliderCurrentValue/2, y: view.center.y - sliderCurrentValue/2, radius: sliderCurrentValue) } |
The circle grows in x and y dimensions downwards when the slider is increased. The only reason half of the current value of the slider was subtracted from the center of both x and y was to make the circle grow in size from the center.
At last run and test your code, following result will be achieved.
Download its source from Github.
Cheers!
1 Comment