方法一:在代碼中,通過 cornerRadius 屬性設(shè)置
/**
* masksToBounds時CALayer的方法;clipsToBounds是UIView的方法
* 最終會調(diào)用masksToBounds方法, 所以用masksToBounds省資源一點。
*/
// self.clipsToBounds = YES;
self.layer.masksToBounds = YES;
self.layer.cornerRadius = 3;
方法二:在 storyboard 或 xib 中通過 KVC 設(shè)置
設(shè)置圓角.png
方法三:在背景是純色的情況下狭姨,用同色鏤空圖覆蓋(取巧).
extension UIView{
/**
添加鏤空邊框
*/
func addHollowBorder() {
let hollowB = UIImageView.init(frame: self.bounds)
hollowB.image = UIImage.init(named: "round_bg")
self.addSubview(hollowB)
}
}
//設(shè)置圓角
roundImageView.image = UIImage.init(named: "ICON108")
roundImageView.addHollowBorder()
方法四:在 UIImage 的類別中添加設(shè)置圓角的方法,通過繪圖的方式實現(xiàn)圓角
extension UIImage{
/**
設(shè)置是否是圓角(默認:3.0,圖片大小)
*/
func isRoundCorner() -> UIImage{
return self.isRoundCorner(3.0, size: self.size)
}
/**
設(shè)置是否是圓角
- parameter radius: 圓角大小
- parameter size: size
- returns: 圓角圖片
*/
func isRoundCorner(radius:CGFloat,size:CGSize) -> UIImage {
let rect = CGRect(origin: CGPoint(x: 0, y: 0), size: size)
//開始圖形上下文
UIGraphicsBeginImageContextWithOptions(size, false, UIScreen.mainScreen().scale)
//繪制路線
CGContextAddPath(UIGraphicsGetCurrentContext(),
UIBezierPath(roundedRect: rect,
byRoundingCorners: UIRectCorner.AllCorners,
cornerRadii: CGSize(width: radius, height: radius)).CGPath)
//裁剪
CGContextClip(UIGraphicsGetCurrentContext())
//將原圖片畫到圖形上下文
self.drawInRect(rect)
CGContextDrawPath(UIGraphicsGetCurrentContext(), .FillStroke)
let output = UIGraphicsGetImageFromCurrentImageContext();
//關(guān)閉上下文
UIGraphicsEndImageContext();
return output
}
/**
設(shè)置圓形圖片
- returns: 圓形圖片
*/
func isCircleImage() -> UIImage {
//開始圖形上下文
UIGraphicsBeginImageContextWithOptions(self.size, false, UIScreen.mainScreen().scale)
//獲取圖形上下文
let contentRef:CGContextRef = UIGraphicsGetCurrentContext()!
//設(shè)置圓形
let rect = CGRectMake(0, 0, self.size.width, self.size.height)
//根據(jù) rect 創(chuàng)建一個橢圓
CGContextAddEllipseInRect(contentRef, rect)
//裁剪
CGContextClip(contentRef)
//將原圖片畫到圖形上下文
self.drawInRect(rect)
//從上下文獲取裁剪后的圖片
let newImage:UIImage = UIGraphicsGetImageFromCurrentImageContext()
//關(guān)閉上下文
UIGraphicsEndImageContext()
return newImage
}
}
//設(shè)置圓形圖片
roundImageView.image = UIImage.init(named: "ICON108")?.isCircleImage()
//設(shè)置圓角
roundImageView.image = UIImage.init(named: "ICON108")?.isRoundCorner()
roundImageView.image = UIImage.init(named: "ICON108")?.isRoundCorner(3.0, size: roundImageView.frame.size)
總結(jié): 如果有多處需要設(shè)置圓角,比如在列表視圖中,建議使用方法三或方法四,因為前兩種方法如果使用的圖層過量會有卡頓現(xiàn)象,而后兩種方法效率較高; 如果只有個別地方需要設(shè)置圓角,可使用方法一和方法二,比較方便
期待你的評論建議O(∩_∩)O~