UIBezierPathの角を丸くする
init(rect: CGRect)
let bezierPath = UIBezierPath(rect: rect)
strokColor.setStroke()
fillColor.setFill()
bezierPath.lineWidth = 3
bezierPath.stroke()
bezierPath.fill()
普通のRectです。角は丸くならない。
init(ovalIn: CGRect)
let bezierPath = UIBezierPath(ovalIn: rect)
strokColor.setStroke()
fillColor.setFill()
bezierPath.lineWidth = 3
bezierPath.stroke()
bezierPath.fill()
楕円なので角はない。Rectによって自動で決まるので調節はできない。
init(roundedRect: CGRect, cornerRadius: CGFloat)
let bezierPath = UIBezierPath(roundedRect: rect, cornerRadius: 50)
strokColor.setStroke()
fillColor.setFill()
bezierPath.lineWidth = 3
bezierPath.stroke()
bezierPath.fill()
4つ角が丸くなる。曲がり具合も調節できる。
上だけ丸くしたいとかはできない。
init(roundedRect: CGRect, byRoundingCorners: UIRectCorner, cornerRadii: CGSize)
let bezierPath = UIBezierPath(roundedRect: rect, byRoundingCorners: .init(rawValue: 0), cornerRadii: CGSize(width: 50, height: 50))
strokColor.setStroke()
fillColor.setFill()
bezierPath.lineWidth = 5
bezierPath.stroke()
bezierPath.fill()
これだと角が丸くなっていません。
パラメーターbyRoundingCornersの.init(rawValue: Int)のInt部分ををいろいろ変更してみた。
Rectの頂点における全ての組み合わせで角を丸くできます。
| 1 | 2 | 3 | 4 |
|---|---|---|---|
![]() |
![]() |
![]() |
![]() |
| 5 | 6 | 7 | 8 |
|---|---|---|---|
![]() |
![]() |
![]() |
![]() |
| 9 | 10 | 11 | 12 |
|---|---|---|---|
![]() |
![]() |
![]() |
![]() |
| 13 | 14 | 15 | 16 |
|---|---|---|---|
![]() |
![]() |
![]() |
![]() |
(追記)
byRoundingCornersはtopLeft, topRight, bottomLeft, bottomRight, allCornersで指定できます。
let bezierPath = UIBezierPath(roundedRect: rect, byRoundingCorners: .topLeft, cornerRadii: CGSize(width: 50, height: 50))
これらは組み合わせで指定できるので、次のようにすると上記の.init(rawValue: 3)よりも直感的に表現できますね。
let bezierPath = UIBezierPath(roundedRect: rect, byRoundingCorners: [.topLeft, .topRight], cornerRadii: CGSize(width: 50, height: 50))
lineCapStyle
let bezierPath = UIBezierPath()
bezierPath.move(to: CGPoint(x: frame.size.width / 2, y: 500))
bezierPath.addLine(to: CGPoint(x: frame.size.width / 2, y: 100))
strokColor.setStroke()
bezierPath.lineWidth = 100
bezierPath.lineCapStyle = .round
bezierPath.stroke()
moveやaddLineを使って描画したパスの角を丸くするには、lineCapStyleをroundに変更する。
パスを閉じる場合はlineJoinStyleを使う。
let bezierPath = UIBezierPath()
bezierPath.move(to: CGPoint(x: frame.size.width / 2, y: 500))
bezierPath.addLine(to: CGPoint(x: frame.size.width / 2, y: 100))
bezierPath.close() // パスを閉じる
strokColor.setStroke()
bezierPath.lineWidth = 100
bezierPath.lineJoinStyle = .round // lineCapStyleではない
bezierPath.stroke()
| lineCapStyle | lineJoinStyle |
|---|---|
![]() |
![]() |

















