swift - How to rounded the corners when I draw rectangle using UIBezierPath points -
i crated rectangle using uibezierpath adding point point, want rounded corners of rectangle seems there no way it. can me ?
class rectanglelayer: cashapelayer { let animationduration: cftimeinterval = 0.5 override init() { super.init() fillcolor = colors.clear.cgcolor linewidth = 5.0 path = rectanglepathstart.cgpath } required init?(coder adecoder: nscoder) { fatalerror("init(coder:) has not been implemented") } var rectanglepathstart: uibezierpath { let rectanglepath = uibezierpath() rectanglepath.movetopoint(cgpoint(x: 0.0, y: 100.0)) rectanglepath.addlinetopoint(cgpoint(x: 0.0, y: -linewidth)) rectanglepath.addlinetopoint(cgpoint(x: 100.0, y: -linewidth)) rectanglepath.addlinetopoint(cgpoint(x: 100.0, y: 100.0)) rectanglepath.addlinetopoint(cgpoint(x: -linewidth / 2, y: 100.0)) rectanglepath.closepath() // fillcolor = colors.red.cgcolor return rectanglepath } }
if want create rounded rectangle, can use
let rectangle = cgrect(x: 0, y: 0, width: 100, height: 100) let path = uibezierpath(roundedrect: rectangle, cornerradius: 20)
if want round of corners, not others, can use
let rectangle = cgrect(x: 0, y: 0, width: 100, height: 100) let path = uibezierpath(roundedrect: rectangle, byroundingcorners: [.topleft, .bottomright], cornerradii: cgsize(width: 35, height: 35))
if want have different corner radius each corner, you'll have add arc each circle individually. comes down calculating center , start , end angle of each arc. you'll find center of each arc inset corner radius corresponding corner of rectangle. example, center of top left corner
cgpoint(x: rectangle.minx + upperleftradius, y: rectangle.miny + upperleftradius)
the start , end angle each arc either straight left, up, down, or right. angles corresponding these directions can seen in uibezierpath documentation.
if need create many rectangles this, can create convenience initializer it
extension uibezierpath { convenience init(roundedrect rect: cgrect, topleftradius r1: cgfloat, toprightradius r2: cgfloat, bottomrightradius r3: cgfloat, bottomleftradius r4: cgfloat) { let left = cgfloat(m_pi) let = cgfloat(1.5*m_pi) let down = cgfloat(m_pi_2) let right = cgfloat(0.0) self.init() addarcwithcenter(cgpoint(x: rect.minx + r1, y: rect.miny + r1), radius: r1, startangle: left, endangle: up, clockwise: true) addarcwithcenter(cgpoint(x: rect.maxx - r2, y: rect.miny + r2), radius: r2, startangle: up, endangle: right, clockwise: true) addarcwithcenter(cgpoint(x: rect.maxx - r3, y: rect.maxy - r3), radius: r3, startangle: right, endangle: down, clockwise: true) addarcwithcenter(cgpoint(x: rect.minx + r4, y: rect.maxy - r4), radius: r4, startangle: down, endangle: left, clockwise: true) closepath() } }
and use this
let path = uibezierpath(roundedrect: rectangle, topleftradius: 30, toprightradius: 10, bottomrightradius: 15, bottomleftradius: 5)
Comments
Post a Comment