在UIImageView上设置角半径不起作用

Mar*_*ell 121 iphone rounded-corners uiimageview ios

我有点失落.我已经使用UIView的图层属性来围绕我的应用程序中的多个元素的角落.但是,这一个UIImageView根本就不符合.不确定我错过了什么.

UIImageView(称为previewImage)包含在表视图单元格中.我已经尝试将cornerRadius属性设置为多个位置(在单元格本身和创建单元格的控制器中)无济于事.

static NSString *CellIdentifier = @"MyTableViewCell";

MyTableViewCell *cell = (MyTableViewCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
    NSArray *topLevelObjects = [[NSBundle mainBundle] loadNibNamed:CellIdentifier owner:self options:nil];
    cell = [topLevelObjects objectAtIndex:0];
    cell.previewImage.layer.cornerRadius = 20; //Made it 20 to make sure it's obvious.
}
Run Code Online (Sandbox Code Playgroud)

有没有关于细胞加载的方式,我错过了?

Eva*_*ski 363

您需要将图层的masksToBounds属性设置为YES:

cell.previewImage.layer.masksToBounds = YES;

这是因为UIImageView控件创建了一个伪子视图来保存UIImage对象.

  • 除非您还栅格化视图(view.layer.shouldRasterize = YES),否则每个帧都需要重新屏蔽所有像素. (19认同)
  • 请注意,这将是一个巨大的性能打击 (14认同)
  • 如果 shouldRasterize 为 false,则您每帧都要支付掩码创建开销。如果 shouldRasterize 为 true 并且您的图层每帧都更改,则您需要支付掩码开销和光栅化开销。理想情况是具有 shouldRasterize = true 的静态(不经常更改)层。 (2认同)

Nai*_*hta 24

另外值得注意的是

  1. 如果您使用aspectFit AND cornerRadius with clipsToBounds/masksToBounds,则不会获得圆角.

即如果你有这个

theImageView.contentMode = .scaleAspectFit
Run Code Online (Sandbox Code Playgroud)

   theImageView.layer.cornerRadius = (theImageView.frame.size.height)/2
    theImageView.clipsToBounds = true
Run Code Online (Sandbox Code Playgroud)

要么

theImageView.layer.masksToBounds = true
Run Code Online (Sandbox Code Playgroud)

不会起作用.你将不得不摆脱aspectFit代码

//theImageView.contentMode = .scaleAspectFit
Run Code Online (Sandbox Code Playgroud)
  1. 确保图像视图宽度和高度相同


Tee*_*aul 22

这应该工作

cell.previewImage.clipsToBounds = YES;

cell.previewImage.layer.cornerRadius = 20;
Run Code Online (Sandbox Code Playgroud)

  • @AlfieHanssen图层有maskToBounds :,视图有clipsToBounds: (4认同)
  • 不确定`clipsToBounds`是后一课的方法.相信它是上面的'masksToBounds`. (3认同)

Dan*_*son 11

我相信你需要设置:

cell.previewImage.layer.masksToBounds = YES;
cell.previewImage.layer.opaque = NO;
Run Code Online (Sandbox Code Playgroud)