在 iOS App 開發(fā)中潘鲫,切圓角的場景有很多。
很多圖片或者 UIView 都需要切圓角浊竟。
很多場景都需要切 UIView 的圓角
切圓角的方式一般有兩種津畸。
第一種振定,使用 UIView 內嵌的 layer,直接來切圓角肉拓,方便快捷后频。
UIImageView *userHeaderImgView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"header"]];
userHeaderImgView.layer.cornerRadius = 39;
userHeaderImgView.layer.masksToBounds = YES;
這樣做的好處:方便快捷,2個屬性就能搞定 UIView 的圓角切割暖途。
這樣做的壞處:切的圓角會產生混合圖層卑惜,影響效率芋浮。
直接使用 UIView.layer 的方式切圓角會有混的圖層
第二種,使用 CAShaperLayer 搭配 UIBezierPath 路徑設置切割路徑,然后把 layer 設置到 UIView 的 mask 屬性上。
UIImageView *userHeaderImgView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"header"]];
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
CAShapeLayer *cornerLayer = [CAShapeLayer layer];
UIBezierPath *cornerPath = [UIBezierPath bezierPathWithRoundedRect:userHeaderImgView.bounds cornerRadius:39];
cornerLayer.path = cornerPath.CGPath;
cornerLayer.frame = userHeaderImgView.bounds;
userHeaderImgView.layer.mask = cornerLayer;
});
這樣做的好處:切割的圓角不會產生混合圖層,提高效率足淆。
這樣做的壞處:代碼量偏多歹鱼,且很多 UIView 都是使用約束布局庭敦,必須搭配 dispatch_after 函數(shù)來設置自身的 mask嚼锄。因為只有在此時沧侥,才能把 UIView 的正確的 bounds 設置到 CAShapeLayer 的 frame 上。
使用 CAShapeLayer 搭配 UIBezierPath 可以避免混合圖層
](https://upload-images.jianshu.io/upload_images/2701794-7a657b30afe942a3.jpg?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
使用 CAShapeLayer 切圓角還有另外一個好處护赊。
常規(guī)的使用 UIView.layer.cornerRadius
& UIView.layer.masksToBounds
雖然方便,但有一點是無法避免的。
那就是:它會把四個角都給切了烛亦。沒有辦法精確的控制切哪一個或者多個角。
可以使用 CAShapeLayer
搭配 UIBezierPath
的 UIRectCorner
參數(shù)
+ (instancetype)bezierPathWithRoundedRect:(CGRect)rect byRoundingCorners:(UIRectCorner)corners cornerRadii:(CGSize)cornerRadii;
來決定UIView 的4個叫知牌,切哪幾個或者是都切了。