设置UIView的圆角这个相信大家都知道怎么做,但有时项目需求是实现某个角的圆角,好的,下面我们就来看看怎么实现吧。
构建一个基于UIView的类别
#import <UIKit/UIKit.h>
/**
* View 圆角
*/
@interface UIView (RectCorner)
- (void)maskToCornerWithRoundingCorners:(UIRectCorner)corner cornerRedius:(CGSize)size;
- (void)setCornerOnTopWithCornerRedius:(CGSize)size;
- (void)setCornerOnBottomWithCornerRedius:(CGSize)size;
- (void)setAllCornerWithCornerRedius:(CGFloat)size;
- (void)setNoneCorner;
@end
#import "UIView+RectCorner.h"
@implementation UIView (RectCorner)
/**
* 设置View的圆角
*
* @param corner 设置哪一个角为圆角
* @param size 圆角的大小
*/
- (void)maskToCornerWithRoundingCorners:(UIRectCorner)corner cornerRedius:(CGSize)size {
UIBezierPath *maskPath;
maskPath = [UIBezierPath bezierPathWithRoundedRect:self.bounds
byRoundingCorners:corner
cornerRadii:size];
CAShapeLayer *maskLayer = [[CAShapeLayer alloc] init];
maskLayer.frame = self.bounds;
maskLayer.path = maskPath.CGPath;
self.layer.mask = maskLayer;
}
/**
* 设置View上面的圆角(左、右)
*/
- (void)setCornerOnTopWithCornerRedius:(CGSize)size {
UIBezierPath *maskPath;
maskPath = [UIBezierPath bezierPathWithRoundedRect:self.bounds
byRoundingCorners:(UIRectCornerTopLeft | UIRectCornerTopRight)
cornerRadii:size];
CAShapeLayer *maskLayer = [[CAShapeLayer alloc] init];
maskLayer.frame = self.bounds;
maskLayer.path = maskPath.CGPath;
self.layer.mask = maskLayer;
}
/**
* 设置View下面的圆角(左、右)
*/
- (void)setCornerOnBottomWithCornerRedius:(CGSize)size {
UIBezierPath *maskPath;
maskPath = [UIBezierPath bezierPathWithRoundedRect:self.bounds
byRoundingCorners:(UIRectCornerBottomLeft | UIRectCornerBottomRight)
cornerRadii:size];
CAShapeLayer *maskLayer = [[CAShapeLayer alloc] init];
maskLayer.frame = self.bounds;
maskLayer.path = maskPath.CGPath;
self.layer.mask = maskLayer;
}
/**
* 设置View四角的圆角
*/
- (void)setAllCornerWithCornerRedius:(CGFloat)size {
UIBezierPath *maskPath;
maskPath = [UIBezierPath bezierPathWithRoundedRect:self.bounds
cornerRadius:size];
CAShapeLayer *maskLayer = [[CAShapeLayer alloc] init];
maskLayer.frame = self.bounds;
maskLayer.path = maskPath.CGPath;
self.layer.mask = maskLayer;
}
/**
* 移除圆角
*/
- (void)setNoneCorner{
self.layer.mask = nil;
}
@end
下面我们看一下怎么调用
- (void)viewDidLoad
{
[super viewDidLoad];
UIImageView * imageView = [[UIImageView alloc] initWithFrame:CGRectMake(50, 50, 100, 100)];
imageView.backgroundColor = [UIColor grayColor];
[imageView maskToCornerWithRoundingCorners:(UIRectCornerTopLeft | UIRectCornerBottomLeft) cornerRedius:CGSizeMake(10, 10)];
[self.view addSubview:imageView];
}
运行结果:
代码实现很简单,希望能帮到需要的人,谢谢!