
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
)