通過創(chuàng)建UIView的分類來實現(xiàn),這樣處理的前提是視圖的frame已經(jīng)固定羞酗,如果是使用了約束驶冒,可以重寫drawrect方法憾筏,并在此設置圓角
.h文件如下
#import <UIKit/UIKit.h>
NS_ASSUME_NONNULL_BEGIN
@interface UIView (CusCorner)
/**
設置指定位置的圓角
@param rectCorner 圓角位置(該變量可使用或運算衰倦,用于同時設置多個圓角)
@param radius 圓角半徑
@param borderWidth 邊框?qū)挾? @param borderColor 邊框顏色
@param fillColor 填充色
@param name 給子layer命名,防止重復設置增加開銷
*/
- (void)setupRoundedCorners:(UIRectCorner)rectCorner
cornerRadius:(CGFloat)radius
borderWidth:(CGFloat)borderWidth
borderColor:( UIColor * _Nullable )borderColor
fillColor:(UIColor * _Nullable)fillColor
layerName:(NSString * _Nullable)name;
@end
NS_ASSUME_NONNULL_END
.m文件如下
#import "UIView+CusCorner.h"
@implementation UIView (CusCorner)
- (void)setupRoundedCorners:(UIRectCorner)rectCorner
cornerRadius:(CGFloat)radius
borderWidth:(CGFloat)borderWidth
borderColor:( UIColor * _Nullable )borderColor
fillColor:(UIColor * _Nullable)fillColor
layerName:(NSString * _Nullable)name{
//設置遮罩
CAShapeLayer *mask=nil;
if ([self.layer.mask.name isEqualToString:name]) {
mask = self.layer.mask;
} else {
mask=[CAShapeLayer layer];
mask.name = name;
}
UIBezierPath * path= [UIBezierPath bezierPathWithRoundedRect:self.bounds byRoundingCorners:rectCorner cornerRadii:CGSizeMake(radius,radius)];
mask.path=path.CGPath;
mask.frame=self.bounds;
self.layer.mask = mask;
//設置邊框及填充色
__block CAShapeLayer *borderLayer = nil;
if (name.length) {
NSArray<CALayer *> *subLayers = self.layer.sublayers;
[subLayers enumerateObjectsUsingBlock:^(CALayer * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
if([obj.name isEqualToString:name]){
borderLayer = (CAShapeLayer *)obj;
*stop = YES;
}
}];
}
if (!borderLayer) {
borderLayer=[CAShapeLayer layer];
borderLayer.name = name;
[self.layer addSublayer:borderLayer];
}
borderLayer.path=path.CGPath;
if (fillColor) {
borderLayer.fillColor = fillColor.CGColor;
}
if (borderColor) {
borderLayer.strokeColor = borderColor.CGColor;
}
if (borderWidth > 0) {
borderLayer.lineWidth = borderWidth;
}
borderLayer.frame = self.bounds;
}
@end
調(diào)用如下
//swift
cusView.setupRoundedCorners([.topLeft , .topRight , .bottomLeft],
cornerRadius: 12,
borderWidth: 0,
borderColor: nil,
fill:UIColor.clear,
layerName: "local")
//oc
[self.cusView setupRoundedCorners:UIRectCornerTopLeft|UIRectCornerTopRight
cornerRadius:15
borderWidth:0
borderColor:nil
fillColor:UIColor.clearColor
layerName:@"layername"];