Make specific corners of UIView round

2019-01-23 19:28发布

I did a bit of research, and I see, there is no easy way to make only top right and top left corners of the UIView round, right?

ps. This code makes all 4 corners round which is smth. I don't want.

  #import <QuartzCore/QuartzCore.h>

 self.layer.cornerRadius = 5;
 self.layer.masksToBounds = YES;

2条回答
爱情/是我丢掉的垃圾
2楼-- · 2019-01-23 19:58

You can do it with this snippet:

// Set top right & left corners
[self setMaskTo:yourView byRoundingCorners:UIRectCornerTopLeft|UIRectCornerTopRight];

EDIT

Sorry, I forgot this

- (void)setMaskTo:(UIView*)view byRoundingCorners:(UIRectCorner)corners
{
    UIBezierPath *rounded = [UIBezierPath bezierPathWithRoundedRect:view.bounds
                                                  byRoundingCorners:corners
                                                        cornerRadii:CGSizeMake(8.0, 8.0)];
    CAShapeLayer *shape = [[CAShapeLayer alloc] init];
    [shape setPath:rounded.CGPath];    
    view.layer.mask = shape;
}

PS: as I said in the comment, if you use things like this when displaying UITableViewCell cells, I've found that it's always a better choice to use background images because this kind of drawing stuff always affects performance.

查看更多
啃猪蹄的小仙女
3楼-- · 2019-01-23 20:03

I tried extensions for the UIView once and it did not work for me because it have caused problems when drawing a cell

I got a better and easier solution now in 2 steps that worked perfectly good :)

1) One line of code (Swift 2.0) - it wounds all 4 corners of a view:

YourView.layer.cornerRadius = 10

2) and one addition in storyboard you add 1 view with regular corners where you need no round corners and adjust constraints as you need : note that small regular corner View should be behind the main view. This is how it looks in storyboard

Here you can see constraints needed for the small view

查看更多
登录 后发表回答