🦁

UIViewで丸を描く

2022/05/29に公開

まずはUIViewを宣言します

ViewController.swift
class ViewController: UIViewController {
	var circleView: UIView!
	override func viewDidLoad() {
		circleView = UIView()
		view.addSubview(circleView)
	}
}

次に、丸の縦、横、位置を定義します
AutoLayoutはなぜか効果がないようで以下の方法で定義します

ViewController.swift
class ViewController: UIViewController {
	var circleView: UIView!
	override func viewDidLoad() {
		circleView = UIView()
		view.addSubview(circleView)
		
+		circleView.frame.size.height = 256
+		circleView.frame.size.width = 256
+		circleView.center = view.center

	}
}

最後はCGLayerを通して枠線などを定義します

ViewController.swift
class ViewController: UIViewController {
	var circleView: UIView!
	override func viewDidLoad() {
		circleView = UIView()
		view.addSubview(circleView)
		
		circleView.frame.size.height = 256
		circleView.frame.size.width = 256
		circleView.center = view.center
+		circleView.layer.borderWidth = 1
+		circleView.layer.cornerRadius = 128
+		circleView.layer.borderColor = UIColor.gray.cgColor

	}
}

Discussion