How to Draw a Simple Rounded Rect in Swift (Rounded Corners)

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

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

}

How to draw a custom rounded rectangle in SWIFT?

I accomplished this by drawing a quadratic.

let dimention: CGFloat = some value

let path = UIBezierPath()
path.move(to: CGPoint(x: dimension/2, y: 0))
path.addQuadCurve(to: CGPoint(x: dimension, y: dimension/2),
controlPoint: CGPoint(x: dimension, y: 0))
path.addQuadCurve(to: CGPoint(x: dimension/2, y: dimension),
controlPoint: CGPoint(x: dimension, y: dimension))
path.addQuadCurve(to: CGPoint(x: 0, y: dimension/2),
controlPoint: CGPoint(x: 0, y: dimension))
path.addQuadCurve(to: CGPoint(x: dimension/2, y: 0),
controlPoint: CGPoint(x: 0, y: 0))
path.close()

let shapeLayer = CAShapeLayer()
shapeLayer.path = path.cgPath
shapeLayer.strokeColor = UIColor.blue.cgColor
shapeLayer.fillColor = UIColor.clear.cgColor
shapeLayer.lineWidth = 1.0
shapeLayer.position = CGPoint(x: 0, y: 0)

self.someView.layer.addSublayer(shapeLayer)

Drawing Rounded Corners Using UIBezierPath

Don't use a shape layer. Use a layer (or a view). Draw the UIBezierPath's path into it and stroke it, and then erase the bottom line by drawing it and stroking it with a .clear blend mode.

Result:

Sample Image

Code (modify as desired; I use here a clear UIView that draws the shape as its draw code):

let p = UIBezierPath(roundedRect: self.bounds,
byRoundingCorners: [.topLeft, .topRight],
cornerRadii: CGSize(width: 4.0, height: 4.0))
UIColor.white.setStroke()
p.stroke()
let p2 = UIBezierPath()
p2.move(to: CGPoint(x:0, y:self.bounds.height))
p2.addLine(to: CGPoint(x:self.bounds.width, y:self.bounds.height))
p2.lineWidth = 2
p2.stroke(with: .clear, alpha: 1)

EDIT Another way would have been to clip out the bottom line area before drawing the rounded rect:

let p1 = UIBezierPath(rect: CGRect(origin:.zero,
size:CGSize(width:self.bounds.width, height:self.bounds.height-2)))
p1.addClip()
let p = UIBezierPath(roundedRect: self.bounds,
byRoundingCorners: [.topLeft, .topRight],
cornerRadii: CGSize(width: 4.0, height: 4.0))
UIColor.white.setStroke()
p.stroke()

How to rounded the corners when I draw rectangle using UIBezierPath points

If all you want to do is create a rounded rectangle, then you can simply use

let rectangle = CGRect(x: 0, y: 0, width: 100, height: 100)
let path = UIBezierPath(roundedRect: rectangle, cornerRadius: 20)

Sample Image

If you want to round some of the corners, but not others, then you 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))

Sample Image

If you want to have a different corner radius for each corner, then you'll have to add the arc for each circle individually. This comes down to calculating the center and the start and end angle of each arc. You'll find that the center of each arc is inset the corner radius from corresponding corner of the rectangle. For example, the center of the top left corner

CGPoint(x: rectangle.minX + upperLeftRadius, y: rectangle.minY + upperLeftRadius)

The start and end angle for each arc will be either straight left, up, down, or right. The angles corresponding to these directions can be seen in the UIBezierPath documentation.

Sample Image

If you need to create many rectangles like this, you can create a convenience initializer for 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 up = 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 it like this

let path = UIBezierPath(roundedRect: rectangle, topLeftRadius: 30, topRightRadius: 10, bottomRightRadius: 15, bottomLeftRadius: 5)

Sample Image

How to draw a just the corners of a rectangle (without lines connecting them)

Here's a custom UIView class that draws itself with the four corners. You can set various properties to get the look you need.

class CornerRect: UIView {
var color = UIColor.black {
didSet {
setNeedsDisplay()
}
}
var radius: CGFloat = 5 {
didSet {
setNeedsDisplay()
}
}
var thickness: CGFloat = 2 {
didSet {
setNeedsDisplay()
}
}
var length: CGFloat = 30 {
didSet {
setNeedsDisplay()
}
}

override func draw(_ rect: CGRect) {
color.set()

let t2 = thickness / 2
let path = UIBezierPath()
// Top left
path.move(to: CGPoint(x: t2, y: length + radius + t2))
path.addLine(to: CGPoint(x: t2, y: radius + t2))
path.addArc(withCenter: CGPoint(x: radius + t2, y: radius + t2), radius: radius, startAngle: CGFloat.pi, endAngle: CGFloat.pi * 3 / 2, clockwise: true)
path.addLine(to: CGPoint(x: length + radius + t2, y: t2))

// Top right
path.move(to: CGPoint(x: frame.width - t2, y: length + radius + t2))
path.addLine(to: CGPoint(x: frame.width - t2, y: radius + t2))
path.addArc(withCenter: CGPoint(x: frame.width - radius - t2, y: radius + t2), radius: radius, startAngle: 0, endAngle: CGFloat.pi * 3 / 2, clockwise: false)
path.addLine(to: CGPoint(x: frame.width - length - radius - t2, y: t2))

// Bottom left
path.move(to: CGPoint(x: t2, y: frame.height - length - radius - t2))
path.addLine(to: CGPoint(x: t2, y: frame.height - radius - t2))
path.addArc(withCenter: CGPoint(x: radius + t2, y: frame.height - radius - t2), radius: radius, startAngle: CGFloat.pi, endAngle: CGFloat.pi / 2, clockwise: false)
path.addLine(to: CGPoint(x: length + radius + t2, y: frame.height - t2))

// Bottom right
path.move(to: CGPoint(x: frame.width - t2, y: frame.height - length - radius - t2))
path.addLine(to: CGPoint(x: frame.width - t2, y: frame.height - radius - t2))
path.addArc(withCenter: CGPoint(x: frame.width - radius - t2, y: frame.height - radius - t2), radius: radius, startAngle: 0, endAngle: CGFloat.pi / 2, clockwise: true)
path.addLine(to: CGPoint(x: frame.width - length - radius - t2, y: frame.height - t2))

path.lineWidth = thickness
path.stroke()
}
}

Sample usage:

let cr = CornerRect(frame: CGRect(x: 0, y: 0, width: 300, height: 500))
cr.color = .yellow
cr.thickness = 5
cr.backgroundColor = .white

Copy and paste that into a playground. Try different values for the properties.

IOS - Drawing rounded corner square

Update for Swift:

The below answer was correct that the time it was written for simple use cases. Things have changed a lot since then so heres an updated answer for swift.

You can create a UIView extension, to add methods to round all corners, or round specific corners. Adding @IBInspectable to the first property means it can be used in interface builder without requiring code

The second function is more complicated and can't be used as an @IBInspectable directly. It will need to be called inside the viewDidLayoutSubviews of the parent to ensure the mask doesn't cut off content as AutoLayout grows / shrinks the content.

extension UIView {

@IBInspectable public var cornerRadius: CGFloat {
set {
layer.cornerRadius = newValue
}
get {
return layer.cornerRadius
}
}

public func roundCorners(corners: UIRectCorner, radius: CGFloat) {
let path = UIBezierPath(roundedRect: bounds, byRoundingCorners: corners, cornerRadii: CGSize(width: radius, height: radius))
let mask = CAShapeLayer()
mask.path = path.cgPath
layer.mask = mask
}
}

Once added to your project you can simply do:

myView.cornerRadius = 4

or

myView.roundCorners(corners: [.topLeft, .topRight], radius: 4)

Very old Objective-c answer:

If you import QuartzCore framework:

#import <QuartzCore/QuartzCore.h>

and add it to your project, you can use the below:

UIView *temp = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 50)];
temp.layer.cornerRadius = 5;

Create a rectangle with just two rounded corners in swift?

In Swift 2.3 you could do so by

let maskPath = UIBezierPath(roundedRect: anyView.bounds,
byRoundingCorners: [.BottomLeft, .BottomRight],
cornerRadii: CGSize(width: 10.0, height: 10.0))

let shape = CAShapeLayer()
shape.path = maskPath.CGPath
view.layer.mask = shape

In Objective-C you could use the UIBezierPath class method

bezierPathWithRoundedRect:byRoundingCorners:cornerRadii:

example implementation-

// set the corner radius to the specified corners of the passed container
- (void)setMaskTo:(UIView*)view byRoundingCorners:(UIRectCorner)corners
{
UIBezierPath *rounded = [UIBezierPath bezierPathWithRoundedRect:view.bounds
byRoundingCorners:corners
cornerRadii:CGSizeMake(10.0, 10.0)];
CAShapeLayer *shape = [[CAShapeLayer alloc] init];
[shape setPath:rounded.CGPath];
view.layer.mask = shape;
}

and call the above method as-

[self setMaskTo:anyView byRoundingCorners:UIRectCornerBottomLeft | UIRectCornerBottomRight];


Related Topics



Leave a reply



Submit