最近项目中需要用到一些视图的某些边界设置为圆角,比如指定一个长方形view,需要设置其左边为圆形,所以就封装一个类来实现指定边界的圆角
1,首先创建一个继承于UIView的分类(由于项目中我需设置一个button的圆角, 所以命名为Btn)
2.在接口文件中设置接口
这里参数:distance 为需要设置圆角的那个边界的高度或宽度
#importtypedef enum { ZSSideRoundLeft, ZSSideRoundRight, ZSSideRoundUp, ZSSideRoundDown} ZSSideRound;@interface UIView (ZSSideRoundBtn)- (void)roundSide:(ZSSideRound)side distance:(CGFloat)distance;@end
3.在.m中实现 (在这里指定边界设置为半圆)
#import "UIView+ZSSideRoundBtn.h"@implementation UIView (ZSSideRoundBtn)- (void)roundSide:(ZSSideRound)side distance:(CGFloat)distance{ UIBezierPath* maskPath; if (side == ZSSideRoundLeft) { maskPath = [UIBezierPath bezierPathWithRoundedRect:self.bounds byRoundingCorners:(UIRectCornerTopLeft | UIRectCornerBottomLeft) cornerRadii:CGSizeMake(distance/2, distance/2)]; } else if (side == ZSSideRoundRight) { maskPath = [UIBezierPath bezierPathWithRoundedRect:self.bounds byRoundingCorners:(UIRectCornerTopRight | UIRectCornerBottomRight) cornerRadii:CGSizeMake(distance/2, distance/2)]; } else if (side == ZSSideRoundUp) { maskPath = [UIBezierPath bezierPathWithRoundedRect:self.bounds byRoundingCorners:(UIRectCornerTopLeft | UIRectCornerTopRight) cornerRadii:CGSizeMake(distance/2, distance/2)]; } else { maskPath = [UIBezierPath bezierPathWithRoundedRect:self.bounds byRoundingCorners:(UIRectCornerBottomLeft | UIRectCornerBottomRight) cornerRadii:CGSizeMake(distance/2, distance/2)]; } // 创建形状图层,设置它的路径 CAShapeLayer* maskLayer = [CAShapeLayer layer]; maskLayer.frame = self.bounds; maskLayer.path = maskPath.CGPath; // 新创建的形状图层设置为图像视图层的面具 self.layer.mask = maskLayer; [self.layer setMasksToBounds:YES];}@end
搞定,以后需要设置一些UIView的子类视图的边界为半圆时,直接引用就OK