12
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

UIBezierPathで矩形のCornerRadiusを別々に指定するサンプルコード

Posted at
Screen Shot 2016-12-13 at 1.38.13.png

Facebook Messengerの吹き出し(上のような画像)のように、それぞれ異なった角丸を持ったViewを作りたかったのですが、
UIBezierPathにはそのようなAPIはありませんでした。

角丸にする角を選択するAPIはあったんですけどね...
これのこと-> init(roundedRect: CGRect, byRoundingCorners: UIRectCorner, cornerRadii: CGSize)

なのでゴリゴリパスを書いて実現しました。

メモレベルですが、せっかくなのでここで共有させていただきます🌳

サンプルコード

func roundedCorners(rect: CGRect, topLeft: CGFloat, topRight: CGFloat, bottomRight: CGFloat, bottomLeft: CGFloat) -> UIBezierPath {

  func radian(_ angle: CGFloat) -> CGFloat {
    return angle * CGFloat(M_PI) / 180
  }

  let path = UIBezierPath()
  path.move(to: CGPoint(x: topLeft, y: 0))

  path.addLine(to: CGPoint(x: rect.maxX - topRight, y: 0))
  path.addArc(withCenter: CGPoint(x: rect.maxX - topRight, y: topRight), radius: topRight, startAngle: radian(-90), endAngle: radian(0), clockwise: true)

  path.addLine(to: CGPoint(x: rect.maxX, y: rect.maxY - bottomRight))
  path.addArc(withCenter: CGPoint(x: rect.maxX - bottomRight, y: rect.maxY - bottomRight), radius: bottomRight, startAngle: radian(0), endAngle: radian(90), clockwise: true)

  path.addLine(to: CGPoint(x: bottomLeft, y: rect.maxY))
  path.addArc(withCenter: CGPoint(x: bottomLeft, y: rect.maxY - bottomLeft), radius: bottomLeft, startAngle: radian(90), endAngle: radian(180), clockwise: true)

  path.addLine(to: CGPoint(x: 0, y: topLeft))
  path.addArc(withCenter: CGPoint(x: topLeft, y: topLeft), radius: topLeft, startAngle: radian(180), endAngle: radian(270), clockwise: true)

  return path
}

使い方

let path = roundedCorners(
  rect: CGRect(x: 0, y: 0, width: 100, height: 36), 
  topLeft: 8,
  topRight: 8,
  bottomRight: 8,
  bottomLeft: 4
)
12
3
0

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
12
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?