UIview 四周加上边框并且自定义view四周的圆角

在.h里  

#importtypedef NS_OPTIONS(NSUInteger, UIBorderSideType) {

UIBorderSideTypeAll  = 0,

UIBorderSideTypeTop = 1 << 0,

UIBorderSideTypeBottom = 1 << 1,

UIBorderSideTypeLeft = 1 << 2,

UIBorderSideTypeRight = 1 << 3,

};

@interface UIView (BorderLine)

- (UIView *)borderForColor:(UIColor *)color borderWidth:(CGFloat)borderWidth borderType:(UIBorderSideType)borderType;

@end


在.m里

#import "UIView+BorderLine.h"

@implementation UIView (BorderLine)

- (UIView *)borderForColor:(UIColor *)color borderWidth:(CGFloat)borderWidth borderType:(UIBorderSideType)borderType

{

if (borderType == UIBorderSideTypeAll)

{

self.layer.borderWidth = borderWidth;

self.layer.borderColor = color.CGColor;

return self;

}

/// 左侧 if (borderType & UIBorderSideTypeLeft)

{

/// 左侧线路径 [self.layer addSublayer:[self addLineOriginPoint:CGPointMake(0.f, 0.f) toPoint:CGPointMake(0.0f, self.frame.size.height) color:color borderWidth:borderWidth]];

} /// 右侧 if (borderType & UIBorderSideTypeRight)

{ /// 右侧线路径 [self.layer addSublayer:[self addLineOriginPoint:CGPointMake(self.frame.size.width, 0.0f) toPoint:CGPointMake( self.frame.size.width, self.frame.size.height) color:color borderWidth:borderWidth]];

} /// top if (borderType & UIBorderSideTypeTop)

{ /// top线路径 [self.layer addSublayer:[self addLineOriginPoint:CGPointMake(0.0f, 0.0f) toPoint:CGPointMake(self.frame.size.width, 0.0f) color:color borderWidth:borderWidth]];

} /// bottom if (borderType & UIBorderSideTypeBottom)

{ /// bottom线路径 [self.layer addSublayer:[self addLineOriginPoint:CGPointMake(0.0f, self.frame.size.height) toPoint:CGPointMake( self.frame.size.width, self.frame.size.height) color:color borderWidth:borderWidth]];

} return self;

}

- (CAShapeLayer *)addLineOriginPoint:(CGPoint)p0 toPoint:(CGPoint)p1 color:(UIColor *)color borderWidth:(CGFloat)borderWidth

{

/// 线的路径 UIBezierPath * bezierPath = [UIBezierPath bezierPath]; [bezierPath moveToPoint:p0];

[bezierPath addLineToPoint:p1]; CAShapeLayer * shapeLayer = [CAShapeLayer layer]; shapeLayer.strokeColor = color.CGColor;

shapeLayer.fillColor = [UIColor clearColor].CGColor; /// 添加路径 shapeLayer.path = bezierPath.CGPath;

/// 线宽度 shapeLayer.lineWidth = borderWidth;

return shapeLayer;

}

@end

方法的调用

初始化个view对象

[view borderForColor:[UIColor redColor] borderWidth:2 borderType:UIBorderSideTypeLeft]; [view borderForColor:[UIColor redColor] borderWidth:2 borderType:UIBorderSideTypeRight]; [self.view addSubview:view];

//设置view四周的圆角大小

UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:view.bounds byRoundingCorners:UIRectCornerBottomLeft | UIRectCornerTopLeft|UIRectCornerBottomRight cornerRadii:CGSizeMake(10,10)]; CAShapeLayer *maskLayer = [[CAShapeLayer alloc] init]; maskLayer.frame = view.bounds; maskLayer.path = maskPath.CGPath; view.layer.mask = maskLayer;

推荐阅读更多精彩内容