How to draw a simple rounded rect in swift (rounded corners)

前端 未结 6 2091
北海茫月
北海茫月 2020-12-25 14:39

I managed to draw a rect :-) But I don\'t know how to draw a rounded rect.

Can someone help me out with the following code how to round the rect?

let         


        
6条回答
  •  佛祖请我去吃肉
    2020-12-25 14:57

    SWIFT 3.x + 4.0 I've modified the example for Swift 3 and added few lines to centralise the rectangle in the UIView

    func roundRect()
    {
        // Size of rounded rectangle
        let rectWidth:CGFloat = 100
        let rectHeight:CGFloat = 80
    
        // Find center of actual frame to set rectangle in middle
        let xf:CGFloat = (self.frame.width  - rectWidth)  / 2
        let yf:CGFloat = (self.frame.height - rectHeight) / 2
    
        let ctx: CGContext = UIGraphicsGetCurrentContext()!
        ctx.saveGState()
    
        let rect = CGRect(x: xf, y: yf, width: rectWidth, height: rectHeight)
        let clipPath: CGPath = UIBezierPath(roundedRect: rect, cornerRadius: rectCornerRadius).cgPath
    
        ctx.addPath(clipPath)
        ctx.setFillColor(rectBgColor.cgColor)
    
    
    
    
        ctx.closePath()
        ctx.fillPath()
        ctx.restoreGState()
    
    }
    

    Full code with screenshots is available on: http://lab.dejaworks.com/uiview-with-rounded-background-designable-in-storyboard/

提交回复
热议问题