self.view.layer.cornerRadius = 5;
self.view.layer.masksToBounds = YES;
複製代碼
使用上面的方式會強制Core Animation
提早渲染屏幕的離屏繪製, 而離屏繪製就會給性能帶來負面影響,會有卡頓的現象出現bash
Core Graphics
- (UIImage *)circleImage {
// NO表明透明
UIGraphicsBeginImageContextWithOptions(self.size, NO, 0.0);
// 得到上下文
CGContextRef ctx = UIGraphicsGetCurrentContext();
// 添加一個圓
CGRect rect = CGRectMake(0, 0, self.size.width, self.size.height);
CGContextAddEllipseInRect(ctx, rect);
// 裁剪
CGContextClip(ctx);
// 將圖片畫上去
[self drawInRect:rect];
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
// 關閉上下文
UIGraphicsEndImageContext();
return image;
}
複製代碼
UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 100, 100)];
imageView.center = CGPointMake(200, 300);
UIImage *anotherImage = [UIImage imageNamed:@"image"];
UIGraphicsBeginImageContextWithOptions(imageView.bounds.size, NO, 1.0);
[[UIBezierPath bezierPathWithRoundedRect:imageView.bounds
cornerRadius:50] addClip];
[anotherImage drawInRect:imageView.bounds];
imageView.image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
[self.view addSubview:imageView];
複製代碼
layer
的mask
屬性實現UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:self.coverImageView.bounds cornerRadius:2];
CAShapeLayer *maskLayer = [CAShapeLayer new];
maskLayer.frame = self.coverImageView.bounds;
maskLayer.path = maskPath.CGPath;
self.coverImageView.layer.mask = maskLayer;
複製代碼