我正在尝试将 UICollectionViewCell
内的 UIImageView
的顶角圆化。它适用于我的第一个代码,但 UICollectionViews 性能大幅下降并开始滞后。为了防止这种情况发生,我尝试创建一个变量并为第一个单元格生成一个 CAShapeLayer,然后将相同的掩码应用于其余单元格。这是我的代码:
在cellForItemAtIndexPath
In if(maskLayer == nil){
UIBezierPath *maskPath;
maskPath = [UIBezierPath bezierPathWithRoundedRect:cell.image.bounds byRoundingCorners:(UIRectCornerTopLeft | UIRectCornerTopRight) cornerRadii:CGSizeMake(3.0, 3.0)];
maskLayer = [[CAShapeLayer alloc] init];
maskLayer.frame = cell.image.bounds;
maskLayer.path = maskPath.CGPath;
}
cell.image.layer.mask = maskLayer;
...
远高于:
@implementation MainViewViewController{
CAShapeLayer *maskLayer;
}
但这不起作用。桅杆仅应用于滚动时进入查看的最后一个单元格,并从其余单元格中移除。这个解决方案甚至可以工作吗?为什么这不起作用?
提前致谢!
编辑 1
尝试按照@debugger的建议创建一个名为RoundedImageView
的UIImageView
子类,现在代码如下所示:
RoundedImageView.m:
#import "RoundedImageView.h"
@implementation RoundedImageView
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
// Initialization code
}
return self;
}
- (void)viewDidLoad{
UIBezierPath *maskPath;
maskPath = [UIBezierPath bezierPathWithRoundedRect:self.bounds byRoundingCorners:(UIRectCornerTopLeft | UIRectCornerTopRight) cornerRadii:CGSizeMake(3.0, 3.0)];
CAShapeLayer *maskLayer = [[CAShapeLayer alloc] init];
maskLayer.frame = self.bounds;
maskLayer.path = maskPath.CGPath;
self.layer.mask = maskLayer;
}
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect
{
UIBezierPath *maskPath;
maskPath = [UIBezierPath bezierPathWithRoundedRect:self.bounds byRoundingCorners:(UIRectCornerTopLeft | UIRectCornerTopRight) cornerRadii:CGSizeMake(3.0, 3.0)];
CAShapeLayer *maskLayer = [[CAShapeLayer alloc] init];
maskLayer.frame = self.bounds;
maskLayer.path = maskPath.CGPath;
self.layer.mask = maskLayer;
}
在我的 Storyboard中,我将 UIImageView 类设置为 RoundedImagView,在我的自定义 UICollectionViewCell 中:
@property (strong, nonatomic) IBOutlet RoundedImageView *image;
但是我根本没有调用 RoundedImageView.m 中的 viewDidLoad 或 drawRect。
最佳答案
为此,您必须创建 UIImageview 扩展类名称 RoundImageview。并在 ViewDidLoad 方法中添加以下代码到类中:
self.contentMode = UIViewContentModeScaleAspectFill;
self.clipsToBounds = YES;
self.layer.cornerRadius = self.frame.size.width/2; // Setting the corner radius
self.layer.masksToBounds = YES;
现在在 viewcontroller 类中,在标题中添加 UIImageview 扩展并初始化如下:
RoundImageview *roundimageview;
并在 cellForRowAtIndexPath 方法中使用以下方法添加图像:
rounfimageview.image = yourimagename
我认为上述方法可行..只需尝试并测试一下即可。
关于ios - 将 CAShapeLayer 应用于单元格内的多个 UIImageViews,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23564439/