設定指定邊界圓角,指定邊界圓角
最近項目中需要用到一些視圖的某些邊界設定為圓角,比如指定一個長方形view,需要設定其左邊為圓形,所以就封裝一個類來實現指定邊界的圓角
1,首先建立一個繼承於UIView的分類(由於項目中我需設定一個button的圓角, 所以命名為Btn)
2.在介面檔案中設定介面
這裡參數:distance 為需要設定圓角的那個邊界的高度或寬度
#import <UIKit/UIKit.h>typedef 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