封裝自定義圓角方向並且可設定投影的View

CocoaJason發表於2018-04-14

#說明: 封裝自定義圓角方向並且可設定投影的View 通過傳入不同的圓角方向以及圓角半徑來實現

點選檢視Demo

點選檢視原始檔 參考文章

CocoaPods支援:

pod 'HZShapeView'
複製程式碼

#原始碼

typedef NS_OPTIONS(NSUInteger, UIRectCorner) {
    UIRectCornerTopLeft     = 1 << 0,     //左上角
    UIRectCornerTopRight    = 1 << 1,    //右上角
    UIRectCornerBottomLeft  = 1 << 2,    //左下角
    UIRectCornerBottomRight = 1 << 3,    //右下角
    UIRectCornerAllCorners  = ~0UL    //全部
};
複製程式碼
@interface HZShapeView : UIView

/**
 建立帶自定義圓角的View
 
 @param frame View的frame
 @param corners 圓角的方向
 @param cornerRadii CGSIze width為圓角的大小
 @return View
 */
+ (instancetype)ShapeViewFrame:(CGRect)frame
             byRoundingCorners:(UIRectCorner)corners
                   cornerRadii:(CGSize)cornerRadii;

- (instancetype)initWithFrame:(CGRect)frame
            byRoundingCorners:(UIRectCorner)corners
                  cornerRadii:(CGSize)cornerRadii;

@end
複製程式碼
@interface HZShapeView()

@property (nonatomic, assign) UIRectCorner corners;
@property (nonatomic, assign) CGSize cornerRadii;

@end

@implementation HZShapeView

+ (Class)layerClass
{
    return [CAShapeLayer class];
}

-(void)layoutSubviews
{
    [super layoutSubviews];
    UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:self.bounds byRoundingCorners:self.corners cornerRadii:self.cornerRadii];
    ((CAShapeLayer *)self.layer).path = maskPath.CGPath;
}

- (void)setBackgroundColor:(UIColor *)backgroundColor
{
    ((CAShapeLayer *)self.layer).fillColor = backgroundColor.CGColor;
}

- (instancetype)initWithFrame:(CGRect)frame byRoundingCorners:(UIRectCorner)corners cornerRadii:(CGSize)cornerRadii;
{
    if (self = [super initWithFrame:frame])
    {
        self.cornerRadii = cornerRadii;
        self.corners = corners;
        self.backgroundColor = [UIColor whiteColor];
    }
    return self;
}

+ (instancetype)ShapeViewFrame:(CGRect)frame
             byRoundingCorners:(UIRectCorner)corners
                   cornerRadii:(CGSize)cornerRadii;
{
    
    return [[HZShapeView alloc] initWithFrame:frame byRoundingCorners:corners cornerRadii:cornerRadii];
}

@end
複製程式碼

#在ViewController中呼叫

    HZShapeView* shapeView = [HZShapeView ShapeViewFrame:CGRectMake(100, 200, 300, 100) byRoundingCorners:UIRectCornerAllCorners cornerRadii:CGSizeMake(10, 100)];
    shapeView.layer.shadowColor = [UIColor redColor].CGColor;
    shapeView.layer.shadowOffset = CGSizeMake(0.f, 0.f);
    shapeView.layer.shadowOpacity = 3.f;
    [self.view addSubview:shapeView];
複製程式碼

#效果如下

Simulator Screen Shot - iPhone 8 Plus - 2018-04-12 at 14.00.05.png

相關文章