這樣就可以減少很多性能開(kāi)支
Objective - C
- (UIImage *)hyb_imageWithCornerRadius:(CGFloat)radius {
CGRect rect = (CGRect){0.f, 0.f, self.size};
UIGraphicsBeginImageContextWithOptions(self.size, NO, UIScreen.mainScreen.scale);
CGContextAddPath(UIGraphicsGetCurrentContext(),
[UIBezierPath bezierPathWithRoundedRect:rect cornerRadius:radius].CGPath);
CGContextClip(UIGraphicsGetCurrentContext());
[self drawInRect:rect];
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return image;
}
swift 版
//MARK:- 設(shè)置圖片圓角
func setImageCornerRadius(radius:CGFloat) -> UIImage{
let rect = CGRectMake(0, 0, self.size.width, self.size.height)
UIGraphicsBeginImageContextWithOptions(self.size, false, UIScreen.mainScreen().scale)
CGContextAddPath(UIGraphicsGetCurrentContext(), UIBezierPath(roundedRect: rect, cornerRadius: radius).CGPath)
CGContextClip(UIGraphicsGetCurrentContext())
self.drawInRect(rect)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndPDFContext()
return image
}
還有一種方法就是
imgView.layer.cornerRadius = 10;
// 這一行代碼是很消耗性能的
imgView.clipsToBounds = YES;
好處是使用簡(jiǎn)單,操作方便。壞處是離屏渲染(off-screen-rendering)需要消耗性能。對(duì)于圖片比較多的視圖上,不建議使用這種方法來(lái)設(shè)置圓角。通常來(lái)說(shuō),計(jì)算機(jī)系統(tǒng)中CPU、GPU、顯示器是協(xié)同工作的。CPU計(jì)算好顯示內(nèi)容提交到GPU,GPU渲染完成后將渲染結(jié)果放入幀緩沖區(qū)。
簡(jiǎn)單來(lái)說(shuō),離屏渲染,導(dǎo)致本該GPU干的活,結(jié)果交給了CPU來(lái)干,而CPU又不擅長(zhǎng)GPU干的活,于是拖慢了UI層的FPS(數(shù)據(jù)幀率),并且離屏需要?jiǎng)?chuàng)建新的緩沖區(qū)和上下文切換,因此消耗較大的性能。