By tom


2012-04-15 23:58:26 8 Comments

Is there a way to set cornerRadius for only top-left and top-right corner of a UIView?

I tried the following, but it end up not seeing the view anymore.

UIView *view = [[UIView alloc] initWithFrame:frame];

CALayer *layer = [CALayer layer];
UIBezierPath *shadowPath = [UIBezierPath bezierPathWithRoundedRect:frame byRoundingCorners:(UIRectCornerTopLeft|UIRectCornerTopRight) cornerRadii:CGSizeMake(3.0, 3.0)];
layer.shadowPath = shadowPath.CGPath;
view.layer.mask = layer;

23 comments

@pierre23 2019-11-26 22:36:43

This would be the simplest answer:

yourView.layer.cornerRadius = 8
yourView.layer.masksToBounds = true
yourView.layer.maskedCorners = [.layerMinXMinYCorner, .layerMaxXMinYCorner]

@Bruno Bieri 2019-10-30 13:19:22

If you're looking for an interface builder only solution there is one for iOS 11 and higher. See my answer here: https://stackoverflow.com/a/58626264

@Sreeraj VR 2019-08-30 15:34:15

In Swift 4.2, Create it via @IBDesignable like this:

@IBDesignable

class DesignableViewCustomCorner: UIView {

    @IBInspectable var cornerRadious: CGFloat = 0 {
        didSet {
            let path = UIBezierPath(roundedRect: self.bounds, byRoundingCorners: [.topLeft, .topRight], cornerRadii: CGSize(width: cornerRadious, height: cornerRadious))
            let mask = CAShapeLayer()
            mask.path = path.cgPath
            self.layer.mask = mask
        }
    }

}

@Sanjay Mishra 2019-05-08 12:46:33

After change bit of code @apinho In swift 4.3 working fine

extension UIView {
func roundCornersWithLayerMask(cornerRadii: CGFloat, corners: UIRectCorner) {
    let path = UIBezierPath(roundedRect: bounds,
                            byRoundingCorners: corners,
                            cornerRadii: CGSize(width: cornerRadii, height: cornerRadii))
    let maskLayer = CAShapeLayer()
    maskLayer.path = path.cgPath
    layer.mask = maskLayer
  }
}

To use this function for you view

YourViewName. roundCornersWithLayerMask(cornerRadii: 20,corners: [.topLeft,.topRight])

@Shakeel Ahmed 2018-09-06 11:08:57

Swift 4 Swift 5 easy way in 1 line

Usage:

//MARK:- Corner Radius of only two side of UIViews
self.roundCorners(view: yourview, corners: [.bottomLeft, .topRight], radius: 12.0)

Function:

//MARK:- Corner Radius of only two side of UIViews
func roundCorners(view :UIView, corners: UIRectCorner, radius: CGFloat){
        let path = UIBezierPath(roundedRect: view.bounds, byRoundingCorners: corners, cornerRadii: CGSize(width: radius, height: radius))
        let mask = CAShapeLayer()
        mask.path = path.cgPath
        view.layer.mask = mask
}

@Jirson Tavera 2019-05-15 19:54:46

Only remember that the corners of your view are not calculated until the viewDidLayoutSubviews is done so you should call roundCorners func inside it

@Vadlapalli Masthan 2019-06-19 13:57:20

can u tell how can i add shadow to this views?

@mojtaba al moussawi 2019-07-02 07:39:29

@ShakeelAhmed this will not work if you want to add a shadow to the view.

@Shakeel Ahmed 2019-07-02 07:40:59

first add corner radius and then add shadow

@mehdi 2019-04-09 12:56:15

Another version of Stephane's answer.

import UIKit

    class RoundCornerView: UIView {
    var corners : UIRectCorner = [.topLeft,.topRight,.bottomLeft,.bottomRight]
        var roundCornerRadius : CGFloat = 0.0
        override func layoutSubviews() {
            super.layoutSubviews()
            if corners.rawValue > 0 && roundCornerRadius > 0.0 {
                self.roundCorners(corners: corners, radius: roundCornerRadius)
            }
        }
        private 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
        }

    }

@Stéphane de Luca 2016-12-17 10:50:48

Swift 4

Pay attention to the fact that if you have layout constraints attached to it, you must refresh this as follows in your UIView subclass:

override func layoutSubviews() {
    super.layoutSubviews()
    roundCorners(corners: [.topLeft, .topRight], radius: 3.0)
}

If you don't do that it won't show up.


And to round corners, use the extension:

extension UIView {
   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
    }
}

@kelin 2018-03-11 10:37:09

It's absolutely not an answer, author was asking how to round particular corners, not how to synchronize corner radius with the layout changes.

@Tiago Couto 2018-08-13 01:30:37

This is answer doesn't make sense.

@Michael 2018-10-13 14:38:56

the answer has been fixed recently.. @kelin

@aznelite89 2019-01-16 09:47:34

this definitely rounded the corner.

@iOS 2018-05-29 08:43:19

In swift 4.1 and Xcode 9.4.1

In iOS 11 this single line is enough:

detailsSubView.layer.maskedCorners = [.layerMinXMinYCorner, .layerMaxXMinYCorner]//Set your view here

See the complete code:

//In viewDidLoad
if #available(iOS 11.0, *){
        detailsSubView.clipsToBounds = false
        detailsSubView.layer.cornerRadius = 10
        detailsSubView.layer.maskedCorners = [.layerMinXMinYCorner, .layerMaxXMinYCorner]
} else {
      //For lower versions
}

But for lower versions

let rectShape = CAShapeLayer()
    rectShape.bounds = detailsSubView.frame
    rectShape.position = detailsSubView.center
    rectShape.path = UIBezierPath(roundedRect: detailsSubView.bounds,    byRoundingCorners: [.topLeft , .topRight], cornerRadii: CGSize(width: 20, height: 20)).cgPath
    detailsSubView.layer.mask = rectShape

Complete code is.

if #available(iOS 11.0, *){
    detailsSubView.clipsToBounds = false
    detailsSubView.layer.cornerRadius = 10
    detailsSubView.layer.maskedCorners = [.layerMinXMinYCorner, .layerMaxXMinYCorner]
}else{
    let rectShape = CAShapeLayer()
    rectShape.bounds = detailsSubView.frame
    rectShape.position = detailsSubView.center
    rectShape.path = UIBezierPath(roundedRect: detailsSubView.bounds,    byRoundingCorners: [.topLeft , .topRight], cornerRadii: CGSize(width: 20, height: 20)).cgPath
    detailsSubView.layer.mask = rectShape
}

If you are using AutoResizing in storyboard write this code in viewDidLayoutSubviews().

override func viewDidLayoutSubviews() {
    super.viewDidLayoutSubviews()

    if #available(iOS 11.0, *){
        detailsSubView.clipsToBounds = false
        detailsSubView.layer.cornerRadius = 10
        detailsSubView.layer.maskedCorners = [.layerMinXMinYCorner, .layerMaxXMinYCorner]
    }else{
        let rectShape = CAShapeLayer()
        rectShape.bounds = detailsSubView.frame
        rectShape.position = detailsSubView.center
        rectShape.path = UIBezierPath(roundedRect: detailsSubView.bounds,    byRoundingCorners: [.topLeft , .topRight], cornerRadii: CGSize(width: 20, height: 20)).cgPath
        detailsSubView.layer.mask = rectShape
    }
}

@Ali Ihsan URAL 2018-12-25 07:46:05

It's not work iOS 9 but works on 11

@jey 2019-02-14 09:25:56

Any solution for ios 9?

@iOS 2019-02-14 09:29:19

@jay let rectShape = CAShapeLayer() rectShape.bounds = detailsSubView.frame rectShape.position = detailsSubView.center rectShape.path = UIBezierPath(roundedRect: detailsSubView.bounds, byRoundingCorners: [.topLeft , .topRight], cornerRadii: CGSize(width: 20, height: 20)).cgPath detailsSubView.layer.mask = rectShape This code can work for iOS 9

@iOS 2019-02-14 09:29:58

@jay check if not inform me

@jey 2019-02-14 09:41:56

Not working for ios 9. Its there is no border on corner part.

@iOS 2019-02-14 09:54:49

@jay I don't have iOS 9 os phone, but I checked in iOS 9 simulator. It's working...How & Where you checked. Can you suggest for me to check in iOS 9

@jey 2019-02-14 10:04:25

i checked in simulator.. here is out put docs.google.com/document/d/…

@David Barta 2015-04-14 09:02:52

Emma: .TopRight and .BottomRight are not working for you perhaps because the call to view.roundCorners is done BEFORE final view bounds are calculated. Note that the Bezier Path derives from the view bounds at the time it is called. For example, if auto layout will narrow the view, the round corners on the right side might be outside the view. Try to call it in viewDidLayoutSubviews, where the view's bound is final.

@Matti 2015-08-26 07:30:50

Thank you. For me, what solved the issue was moving the call to the implementation given by "Arbitur" from viewDidLoad and viewWillAppear to viewDidAppear. I could do so since my control is initially set to hidden.

@Ashish Kakkad 2016-01-12 11:57:54

You are right. It will create issue with autolayout and you have done good job.

@MrMins 2018-08-02 00:18:44

Swift 4

extension UIView {

    func roundTop(radius:CGFloat = 5){
        self.clipsToBounds = true
        self.layer.cornerRadius = radius
        if #available(iOS 11.0, *) {
            self.layer.maskedCorners = [.layerMaxXMinYCorner, .layerMinXMinYCorner]
        } else {
            // Fallback on earlier versions
        }
    }

    func roundBottom(radius:CGFloat = 5){
        self.clipsToBounds = true
        self.layer.cornerRadius = radius
        if #available(iOS 11.0, *) {
            self.layer.maskedCorners = [.layerMaxXMaxYCorner, .layerMinXMaxYCorner]
        } else {
            // Fallback on earlier versions
        }
    }
}

@Shakti 2019-04-05 14:05:54

You saved my day in my case I had to make the table view rounded for particular cells

@Nikita Patil 2019-10-24 07:13:17

Perfect ans according my requirement. I used all the answer, nothing worked for me, but your answer helped me and solved my problem.

@Sergey Belous 2017-06-16 12:14:59

And finally… there is CACornerMask in iOS11! With CACornerMask it can be done pretty easy:

let view = UIView()
view.clipsToBounds = true
view.layer.cornerRadius = 10
view.layer.maskedCorners = [.layerMaxXMinYCorner, .layerMinXMinYCorner] // Top right corner, Top left corner respectively

@cornr 2017-11-13 12:05:00

this definitely works best. we always had issues with the other solutions when rounding the edges of dynamically sizing tableview cells.

@Aliens 2018-01-16 15:53:40

Project must support iOS 11 onwards in order to use that solution.

@Sergey Belous 2018-01-17 20:08:07

@Aliens and… I mentioned that.

@SHEBIN 2018-01-29 19:11:25

what will do for older version? self.layer.maskedCorners = [.layerMaxXMaxYCorner, .layerMinXMaxYCorner,.layerMaxXMinYCorner]

@Sergey Belous 2018-01-30 08:11:46

@SHEBIN, try solutions from the other answers on this page

@Cloud9999Strife 2018-10-03 12:37:36

The other answers don't work when rotating the device, this code works for rotation and allows you to round certain corners, this should be the accepted answer.

@eharo2 2019-02-25 15:18:10

Simple is beautiful

@Muhammad Nayab 2019-12-06 11:07:52

Do not needed to set "view.clipsToBounds = true". Else it can have some side-effects on Shadow(if you have applied shadows as well)

@reza_khalafi 2018-02-27 07:10:10

iOS 11 , Swift 4
And you can try this code:

if #available(iOS 11.0, *) {
   element.clipsToBounds = true
   element.layer.cornerRadius = CORNER_RADIUS
   element.layer.maskedCorners = [.layerMaxXMaxYCorner]
} else {
   // Fallback on earlier versions
}

And you can using this in table view cell.

@Alen Liang 2018-10-28 09:49:31

that's the right answer for today's coding. bye bye to mask layer.

@fujianjin6471 2019-06-03 10:55:51

This must be the best answer!

@Arbitur 2014-12-04 12:12:18

Here is a Swift version of @JohnnyRockex answer

extension UIView {

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

}

view.roundCorners([.topLeft, .bottomRight], radius: 10)

Note

If you're using Auto Layout, you'll need to subclass your UIView and call roundCorners in the view's layoutSubviews for optimal effect.

class View: UIView {
    override func layoutSubviews() {
        super.layoutSubviews()

        self.roundCorners([.topLeft, .bottomLeft], radius: 10)
    }
}

@Onichan 2015-03-25 10:06:20

Great extension. However: .TopRight and .BottomRight don't seem to work for me.

@Arbitur 2015-07-17 06:57:01

When doesnt those edges work? When you use only one of those edges or both or all edges? Because I havent ran into this problem.

@fahrulazmi 2015-09-17 07:53:10

on Swift 2: view.roundCorners([.TopLeft , .BottomLeft], radius: 10)

@Mattias 2015-09-24 14:09:22

This is a beautiful solution, but I can't seem to round any other corner but .TopLeft. Could this be due to AutoLayout or something? I don't know where to look, hehe.

@Mattias 2015-09-24 14:23:53

Can't edit my comment but I was calling the function in the wrong function. Calling it in an

@dosdos 2015-10-28 09:50:06

It's not working on the Right, because your view's bounds is not yet well defined with autolayout... I'm currently facing the same issue.

@Arbitur 2015-10-28 10:02:29

@dosdos Subclass that view and in layoutSubviews round the corners of self.

@Vic 2016-02-25 10:07:24

just to make it clear, like what Arbitur said: override func viewDidLayoutSubviews() {viewToRound.roundCorners([.TopLeft, .TopRight], radius: BUTTON_RADIUS)}

@Frédéric Adda 2016-05-02 09:30:39

If you are in a UIView, use override func layoutSubviews() { super.layoutSubviews() // Round the bottom-left and top-right corners self.label.roundCorners([.BottomLeft, .TopRight], radius: CORNER_RADIUS) }

@zgjie 2016-05-18 08:41:51

If you use auto layout, and have not the reference to the view want to round, you can call .layoutIfNeeded(), then this method.

@Kevin Sabbe 2017-02-28 12:46:40

issue => That's work perfectly! Except that my view is resizing when Im using your function :( Any ideas??

@user1673099 2017-04-12 06:42:08

not working for bottom. i.e. bottomLeft & bottomRight

@Van Du Tran 2017-11-30 01:34:51

I'm on Swift 4, use Auto-Layout, and I get a blank screen lol (view is invisible)

@Van Du Tran 2017-11-30 01:40:13

Calling layoutIfNeeded() did the trick. Just a note, if you want shadow on your view, shadow won't appear.

@u.gen 2018-06-15 15:03:36

@Arbitur in swift 4 this is resizing the view and making it shorter. Any idea why? In override func awakeFromNib() I call self.scheduledView.roundCorners([.topLeft, .topRight], radius: 3.0) then layoutIfNeeded()

@Arbitur 2018-06-15 15:06:10

@u.gen as I've stated in my answer. Place the code inside layoutSubViews instead.

@Anuran Barman 2019-01-23 06:08:45

awesome small solution. both topLeft and topRight are working.

@Johnny Rockex 2013-08-22 09:38:27

Here is a short method implemented like this:

- (void)viewDidLoad {
    [super viewDidLoad];
    UIButton *openInMaps = [UIButton new];
    [openInMaps setFrame:CGRectMake(15, 135, 114, 70)];
    openInMaps = (UIButton *)[self roundCornersOnView:openInMaps onTopLeft:NO topRight:NO bottomLeft:YES bottomRight:NO radius:5.0];
}

- (UIView *)roundCornersOnView:(UIView *)view onTopLeft:(BOOL)tl topRight:(BOOL)tr bottomLeft:(BOOL)bl bottomRight:(BOOL)br radius:(float)radius {

    if (tl || tr || bl || br) {
        UIRectCorner corner = 0;
        if (tl) {corner = corner | UIRectCornerTopLeft;}
        if (tr) {corner = corner | UIRectCornerTopRight;}
        if (bl) {corner = corner | UIRectCornerBottomLeft;}
        if (br) {corner = corner | UIRectCornerBottomRight;}

        UIView *roundedView = view;
        UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:roundedView.bounds byRoundingCorners:corner cornerRadii:CGSizeMake(radius, radius)];
        CAShapeLayer *maskLayer = [CAShapeLayer layer];
        maskLayer.frame = roundedView.bounds;
        maskLayer.path = maskPath.CGPath;
        roundedView.layer.mask = maskLayer;
        return roundedView;
    }
    return view;
}

@kiran 2018-02-16 15:52:52

What about setting color ? maskLayer.borderWidth = 10; maskLayer.borderColor = [UIColor redColor].CGColor; its not working for me sir.

@Johnny Rockex 2018-02-20 16:21:55

@kiran a mask doesn't have a colour, you could add a second CAShapeLayer if you want to have a border

@Yunus Nedim Mehel 2012-10-31 17:38:04

I am not sure why your solution did not work but the following code is working for me. Create a bezier mask and apply it to your view. In my code below I was rounding the bottom corners of the _backgroundView with a radius of 3 pixels. self is a custom UITableViewCell:

UIBezierPath *maskPath = [UIBezierPath
    bezierPathWithRoundedRect:self.backgroundImageView.bounds
    byRoundingCorners:(UIRectCornerBottomLeft | UIRectCornerBottomRight)
    cornerRadii:CGSizeMake(20, 20)
];

CAShapeLayer *maskLayer = [CAShapeLayer layer];

maskLayer.frame = self.bounds;
maskLayer.path = maskPath.CGPath;

self.backgroundImageView.layer.mask = maskLayer;

Swift version with some improvements:

let path = UIBezierPath(roundedRect:viewToRound.bounds, byRoundingCorners:[.TopRight, .BottomLeft], cornerRadii: CGSizeMake(20, 20))
let maskLayer = CAShapeLayer()

maskLayer.path = path.CGPath
viewToRound.layer.mask = maskLayer

Swift 3.0 version:

let path = UIBezierPath(roundedRect:viewToRound.bounds,
                        byRoundingCorners:[.topRight, .bottomLeft],
                        cornerRadii: CGSize(width: 20, height:  20))

let maskLayer = CAShapeLayer()

maskLayer.path = path.cgPath
viewToRound.layer.mask = maskLayer

Swift extension here

@Rainer Liao 2015-08-20 09:36:04

try in textfield. success in left, failure in right

@Lucho 2015-09-09 19:31:49

@RainerLiao i had the same issue, i did all this on the viewDidLoad method, move it to viewDidAppear and it worked.

@Chanaka Caldera 2016-09-21 12:19:38

how can I set this to work for any device. this only works fine for the simulator size int the storyboard. ex: if the simulator size is 6s it works fine for 6s, but not of others. how can I overcome this.

@Rob 2016-10-18 12:05:33

Little syntax error in Swift 3 version: path.CGPath should be path.cgPath

@Matthew Knippen 2016-12-13 17:39:02

@RainerLiao if you don't want it to flick as the view appears, change it to viewWillAppear instead. This also works.

@Andrey Gordeev 2017-03-02 07:06:18

Please note that masks are quite CPU-consuming.

@user1673099 2017-04-12 06:41:43

not working for bottom. i.e. bottomLeft & bottomRight

@Nazmul Hasan 2017-08-06 08:08:18

don't forget to add viewToRound.layoutIfNeeded() Thanks

@Yunus Nedim Mehel 2018-07-03 12:46:17

@Saeed Rahmatolahi 2018-07-24 04:54:31

@YunusNedimMehel this is working well But how can I use it in my view class in IBDesignable for changing the Edge corners in story board ?

@Yunus Nedim Mehel 2018-07-24 08:47:11

Glad to hear. Sadly, I don't think you can do this on IB since this is an operation on the .layer.

@apinho 2016-11-02 15:19:48

A lovely extension to reuse Yunus Nedim Mehel solution

Swift 2.3

extension UIView {
func roundCornersWithLayerMask(cornerRadii: CGFloat, corners: UIRectCorner) {
    let path = UIBezierPath(roundedRect: bounds,
                            byRoundingCorners: corners,
                            cornerRadii: CGSize(width: cornerRadii, height: cornerRadii))
    let maskLayer = CAShapeLayer()
    maskLayer.path = path.CGPath
    layer.mask = maskLayer
} }

Usage

let view = UIView()
view.roundCornersWithLayerMask(10,[.TopLeft,.TopRight])

@Aggressor 2018-04-19 15:54:27

Nice clean solution

@jfmg 2016-01-27 11:11:10

This is how you can set a corner radius for each corner of a button with Xamarin in C#:

var maskPath = UIBezierPath.FromRoundedRect(MyButton.Bounds, UIRectCorner.BottomLeft | UIRectCorner.BottomRight,
    new CGSize(10.0, 10.0));
var maskLayer = new CAShapeLayer
{
    Frame = MyButton.Bounds,
    Path = maskPath.CGPath
};
MyButton.Layer.Mask = maskLayer;

@Kurt Revis 2012-04-16 00:13:20

Swift code example here: https://stackoverflow.com/a/35621736/308315


Not directly. You will have to:

  1. Create a CAShapeLayer
  2. Set its path to be a CGPathRef based on view.bounds but with only two rounded corners (probably by using +[UIBezierPath bezierPathWithRoundedRect:byRoundingCorners:cornerRadii:])
  3. Set your view.layer.mask to be the CAShapeLayer

@jjxtra 2012-06-18 21:15:15

Be warned this will hurt performance if you do it on more than just a couple of views...

@xi.lin 2016-04-18 02:06:42

@jjxtra So what's the best way to do it without much performance loss? I want to show it in UITableViewCell.

@codrut 2017-10-09 08:22:39

@xi.lin from what I remember setting layer.shouldRasterize == YES improves speed 5 times or so. But the docs say it only works if you work with non-transparent cells. Give it a shot.

@Spydy 2015-01-09 07:57:47

    // Create the path (with only the top-left corner rounded)
UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:view.bounds 
                           byRoundingCorners:(UIRectCornerBottomLeft | UIRectCornerBottomRight) 
                           cornerRadii:CGSizeMake(7.0, 7.0)];

// Create the shape layer and set its path
CAShapeLayer *maskLayer = [CAShapeLayer layer];
maskLayer.frame = cell.stripBlackImnageView.bounds;
maskLayer.path = maskPath.CGPath; 
// Set the newly created shapelayer as the mask for the image view's layer
view.layer.mask = maskLayer;

@apouche 2015-09-19 14:10:41

All of the answers already given are really good and valid (especially Yunus idea of using the mask property).

However I needed something a little more complex because my layer could often change sizes which mean I needed to call that masking logic every time and this was a little bit annoying.

I used swift extensions and computed properties to build a real cornerRadii property which takes care of auto updating the mask when layer is layed out.

This was achieved using Peter Steinberg great Aspects library for swizzling.

Full code is here:

extension CALayer {
  // This will hold the keys for the runtime property associations
  private struct AssociationKey {
    static var CornerRect:Int8 = 1    // for the UIRectCorner argument
    static var CornerRadius:Int8 = 2  // for the radius argument
  }

  // new computed property on CALayer
  // You send the corners you want to round (ex. [.TopLeft, .BottomLeft])
  // and the radius at which you want the corners to be round
  var cornerRadii:(corners: UIRectCorner, radius:CGFloat) {
    get {
      let number = objc_getAssociatedObject(self, &AssociationKey.CornerRect)  as? NSNumber ?? 0
      let radius = objc_getAssociatedObject(self, &AssociationKey.CornerRadius)  as? NSNumber ?? 0
      return (corners: UIRectCorner(rawValue: number.unsignedLongValue), radius: CGFloat(radius.floatValue))
    }
    set (v) {
      let radius = v.radius
      let closure:((Void)->Void) = {
        let path = UIBezierPath(roundedRect: self.bounds, byRoundingCorners: v.corners, cornerRadii: CGSize(width: radius, height: radius))
        let mask = CAShapeLayer()
        mask.path = path.CGPath
        self.mask = mask
      }
      let block: @convention(block) Void -> Void = closure
      let objectBlock = unsafeBitCast(block, AnyObject.self)
      objc_setAssociatedObject(self, &AssociationKey.CornerRect, NSNumber(unsignedLong: v.corners.rawValue), .OBJC_ASSOCIATION_RETAIN)
      objc_setAssociatedObject(self, &AssociationKey.CornerRadius, NSNumber(float: Float(v.radius)), .OBJC_ASSOCIATION_RETAIN)
      do { try aspect_hookSelector("layoutSublayers", withOptions: .PositionAfter, usingBlock: objectBlock) }
      catch _ { }
    }
  }
}

I wrote a simple blog post explaining this.

@user4269028 2015-09-18 09:35:48

Try this code,

UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:view.bounds byRoundingCorners:( UIRectCornerTopLeft | UIRectCornerTopRight) cornerRadii:CGSizeMake(5.0, 5.0)];

CAShapeLayer *maskLayer = [[CAShapeLayer alloc] init];
maskLayer.frame = self.view.bounds;
maskLayer.path  = maskPath.CGPath;

view.layer.mask = maskLayer;

@Nate Symer 2012-04-16 02:26:41

A way to do this programmatically would be to create a UIView over the top part of the UIView that has the rounded corners. Or you could hide the top underneath something.

@Spencer Williams 2012-10-31 17:30:12

Why is this downvoted? It's a quick, effective solution

@Arbitur 2014-12-12 21:03:38

Its a very ugly solution :P

@Matt Hudson 2012-04-16 00:11:44

The easiest way would be to make a mask with a rounded corner layer.

CALayer *maskLayer = [CALayer layer];
maskLayer.frame = CGRectMake(0,0,maskWidth ,maskHeight);
maskLayer.contents = (__bridge id)[[UIImage imageNamed:@"maskImageWithRoundedCorners.png"] CGImage];

aUIView.layer.mask = maskLayer;

And don't forget to:

#import <QuartzCore/QuartzCore.h>

Related Questions

Sponsored Content

3 Answered Questions

[SOLVED] Different cornerRadius for each corner Swift 3 - iOS

  • 2016-11-09 01:01:57
  • Vinodha Sundaramoorthy
  • 11373 View
  • 15 Score
  • 3 Answer
  • Tags:   ios swift3 cornerradius

14 Answered Questions

[SOLVED] Rounded UIView using CALayers - only some corners - How?

10 Answered Questions

[SOLVED] Setting Corner Radius on UIImageView not working

21 Answered Questions

[SOLVED] Giving UIView rounded corners

32 Answered Questions

[SOLVED] UIView with rounded corners and drop shadow?

20 Answered Questions

10 Answered Questions

5 Answered Questions

[SOLVED] UiView with top left and right rounded corners and border

2 Answered Questions

[SOLVED] My corner radius is applying to only one corner

  • 2016-09-17 19:43:43
  • Slavik
  • 220 View
  • 0 Score
  • 2 Answer
  • Tags:   ios swift uiview

Sponsored Content