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