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

7

28

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 canvas = UIGraphicsGetCurrentContext()
rec = CGRectMake(0, 0, 40, 40);

//var maskPath = UIBezierPath(roundedRect: rec, byRoundingCorners: .BottomLeft | .BottomRight, cornerRadii: CGSize(width: 3, height: 3))

CGContextAddRect(canvas, rec);
CGContextFillPath(canvas);
Kliman answered 21/5, 2015 at 8:47 Comment(3)
Refer this Link: #25591889Juvenility
Thanks, but this is reffering to rounded UIView and a rect in it. I really would like to round the rect itself.Kliman
I edit the content of my post I believe that it is what you are looking for now.Chough
F
24

//Put this code in ur drawRect

Objective - C

 - (void)drawRect:(CGRect)rect
{

CGContextRef ctx = UIGraphicsGetCurrentContext();
CGContextSaveGState(ctx);


 CGPathRef clippath = [UIBezierPath bezierPathWithRoundedRect:CGRectMake(x,y, width, height) cornerRadius:6].CGPath;
CGContextAddPath(ctx, clippath);

CGContextSetFillColorWithColor(ctx, self.color.CGColor);

CGContextClosePath(ctx);
CGContextFillPath(ctx);

[self.color set];


[_path closePath]; // Implicitly does a line between p4 and p1
[_path fill]; // If you want it filled, or...
[_path stroke]; // ...if you want to draw the outline.
CGContextRestoreGState(ctx);
}

Swift 3

func drawRect(rect : CGRect)
{
// Size of rounded rectangle
let rectWidth = rect.width
let rectHeight = rect.height

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

}
Fanchet answered 21/5, 2015 at 9:3 Comment(4)
I tried to translate this in swift, but I get error with converting UIBezierPath to CGPath. Could you please add missing statement in my existing code ?Kliman
clippath=(UIBezierPath(roundedRect: CGRectMake(0, 0, 0, 0), cornerRadius: 0)).CGPathFanchet
Magic variable _path in solutionPhono
let ctx: CGContext = UIGraphicsGetCurrentContext()! ------------- when build is nil value how to fixMaxie
C
27

How to create a rounded corner rectangle using BezierPath

 var roundRect = UIBezierPath(roundedRect: <CGRect>, byRoundingCorners: <UIRectCorner>, cornerRadii: <CGSize>)

Or for an example with values:

var roundRect = UIBezierPath(roundedRect: CGRectMake(0, 0, 100, 100), byRoundingCorners:.AllCorners, cornerRadii: CGSizeMake(16.f, 16.f))

Swift 5

var roundRect = UIBezierPath(roundedRect: CGRect(x: 0, y: 0, width: 100, height: 100), byRoundingCorners:.allCorners, cornerRadii: CGSize(width: 16.0, height: 16.0))
Chough answered 21/5, 2015 at 9:8 Comment(2)
Thats not what I am looking for. You do something with an UIImageView.Kliman
Thanks a lot . I upvoted yours, because its the correct answer. I accepted mukus answer, because he was faster in replying. ThanksKliman
F
24

//Put this code in ur drawRect

Objective - C

 - (void)drawRect:(CGRect)rect
{

CGContextRef ctx = UIGraphicsGetCurrentContext();
CGContextSaveGState(ctx);


 CGPathRef clippath = [UIBezierPath bezierPathWithRoundedRect:CGRectMake(x,y, width, height) cornerRadius:6].CGPath;
CGContextAddPath(ctx, clippath);

CGContextSetFillColorWithColor(ctx, self.color.CGColor);

CGContextClosePath(ctx);
CGContextFillPath(ctx);

[self.color set];


[_path closePath]; // Implicitly does a line between p4 and p1
[_path fill]; // If you want it filled, or...
[_path stroke]; // ...if you want to draw the outline.
CGContextRestoreGState(ctx);
}

Swift 3

func drawRect(rect : CGRect)
{
// Size of rounded rectangle
let rectWidth = rect.width
let rectHeight = rect.height

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

}
Fanchet answered 21/5, 2015 at 9:3 Comment(4)
I tried to translate this in swift, but I get error with converting UIBezierPath to CGPath. Could you please add missing statement in my existing code ?Kliman
clippath=(UIBezierPath(roundedRect: CGRectMake(0, 0, 0, 0), cornerRadius: 0)).CGPathFanchet
Magic variable _path in solutionPhono
let ctx: CGContext = UIGraphicsGetCurrentContext()! ------------- when build is nil value how to fixMaxie
O
19

@muku answer in Swift 4.x+:

override func draw(_ rect: CGRect) {
  super.draw(rect)

  let clipPath = UIBezierPath(roundedRect: rect, cornerRadius: 6.0).cgPath

  let ctx = UIGraphicsGetCurrentContext()!
  ctx.addPath(clipPath)
  ctx.setFillColor(UIColor.red.cgColor)

  ctx.closePath()
  ctx.fillPath()
}
Obese answered 28/2, 2016 at 9:1 Comment(4)
CGPath is now cgPathFurrow
this is not swift 4.Myxomycete
let ctx = UIGraphicsGetCurrentContext()! ------------- when build is nil value how to fixMaxie
Simplest solutionNickey
P
10

Swift 5, 4

iOS 11

override func draw(_ rect: CGRect) {
  super.draw(rect)

  guard let context = UIGraphicsGetCurrentContext() else { return }

  context.saveGState()
  defer { context.restoreGState() }

  let path = UIBezierPath(
    roundedRect: rect,
    byRoundingCorners: [.topLeft, .topRight],
    cornerRadii: CGSize(width: 4, height: 4)
  )

  context.addPath(path.cgPath)
  context.closePath()

  context.setStrokeColor(UIColor.red.cgColor)
  context.strokePath()
}

Phototherapy answered 3/8, 2018 at 16:59 Comment(0)
M
5

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/

Designable UIView with Rounded Rectangle Background

Motorbike answered 23/10, 2016 at 16:8 Comment(2)
@AbdulYasin "not so surprising" pardon ? if you don't have any basic skill, you can't blame other for this. I've added a link with working code and screenshots. You can check and see what is not working for you. Regards.Motorbike
@Motorbike Great work, thank you! However, I am wondering if it’s possible to extend your solution so that every corner can have a different radius?Adalie
M
3
override func draw(_ rect: CGRect) {

    let bezierPath = UIBezierPath(roundedRect: CGRect(x: 0, y: 0, width: 40.0, height: 40.0), cornerRadius: 3.0)
    UIColor.yellow.setFill()
    bezierPath.fill()

}
Myxomycete answered 6/3, 2018 at 19:23 Comment(0)
A
1

The question didn't specifically exclude drawing in MacOS, so this works (MacOS 12) in Swift for drawing into a current graphic context, such as in an NSView's draw() method:

let ctx = NSGraphicsContext.current!.cgContext

ctx.setStrokeColor(NSColor.blue)

let path = NSBezierPath(roundedRect: bds, xRadius: 6.0, yRadius: 6.0)
path.lineWidth = 8.0
path.stroke()

Choose your color, radii, and linewidth according to your needs.

Affray answered 29/10, 2023 at 18:5 Comment(2)
"The question didn't specifically exclude drawing in MacOS" - I have no issue with your answer but the question is tagged iOS, not macOS.Disaster
You're right, I was just looking at the tile. FWIW, my Google search for "MacOS swift drawing roundrect" led to this page.Affray

© 2022 - 2025 — McMap. All rights reserved.