LoginSignup
13
15

More than 5 years have passed since last update.

UIBezierPathの角を丸くする

Last updated at Posted at 2016-12-09

UIBezierPathの角を丸くする

init(rect: CGRect)

let bezierPath = UIBezierPath(rect: rect)
strokColor.setStroke()
fillColor.setFill()
bezierPath.lineWidth = 3
bezierPath.stroke()
bezierPath.fill()

screenshot.png

普通のRectです。角は丸くならない。

init(ovalIn: CGRect)

let bezierPath = UIBezierPath(ovalIn: rect)
strokColor.setStroke()
fillColor.setFill()
bezierPath.lineWidth = 3
bezierPath.stroke()
bezierPath.fill()

screenshot.png

楕円なので角はない。Rectによって自動で決まるので調節はできない。

init(roundedRect: CGRect, cornerRadius: CGFloat)

let bezierPath = UIBezierPath(roundedRect: rect, cornerRadius: 50)
strokColor.setStroke()
fillColor.setFill()
bezierPath.lineWidth = 3
bezierPath.stroke()
bezierPath.fill()

screenshot.png

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()

screenshot.png

これだと角が丸くなっていません。
パラメーターbyRoundingCorners.init(rawValue: Int)Int部分ををいろいろ変更してみた。
Rectの頂点における全ての組み合わせで角を丸くできます。

1 2 3 4
screenshot.png screenshot.png screenshot.png screenshot.png
5 6 7 8
screenshot.png screenshot.png screenshot.png screenshot.png
9 10 11 12
screenshot.png screenshot.png screenshot.png screenshot.png
13 14 15 16
screenshot.png screenshot.png screenshot.png screenshot.png

(追記)

byRoundingCornerstopLeft, 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()

moveaddLineを使って描画したパスの角を丸くするには、lineCapStyleroundに変更する。

パスを閉じる場合は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
screenshot.png screenshot.png
13
15
5

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
13
15