iOS的UIView提供了基本的設(shè)置圓角的方法,即:
? ? ? ? view.layer.cornerRadius= cornerRadius;
但是在項(xiàng)目中常常遇到需要在指定位置設(shè)置圓角,當(dāng)然我們常常用UI切圖的方式來(lái)實(shí)現(xiàn),但是我們用代碼也可以實(shí)現(xiàn)這一效果。
首先,iOS 11以上系統(tǒng)也提供了設(shè)置方法,即在設(shè)置cornerRadius的基礎(chǔ)上,再設(shè)置圓角的方向maskedCorners:
? ? ? ? view.layer.maskedCorners = (CACornerMask)(UIRectCornerTopLeft|UIRectCornerTopRight);
而在iOS 11.0以前我們就需要用貝塞爾曲線來(lái)繪制圓角了,即:
? ??????UIBezierPath * path = [UIBezierPath bezierPathWithRoundedRect:view.bounds byRoundingCorners:UIRectCornerTopLeft|UIRectCornerTopRight cornerRadii:CGSizeMake(cornerRadius, cornerRadius)];
? ? ? ? CAShapeLayer*maskLayer = [[CAShapeLayeralloc]init];
? ? ? ? maskLayer.frame=view.bounds;
? ? ? ? maskLayer.path= path.CGPath;
? ? ? ? view.layer.mask= maskLayer;