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

问题描述 投票:116回答:9

我有点失落。我已经使用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.
}

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

iphone ios uiimageview rounded-corners
9个回答
355
投票

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

cell.previewImage.layer.masksToBounds = YES;

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


22
投票

另外值得注意的是

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

即如果你有这个

theImageView.contentMode = .scaleAspectFit

   theImageView.layer.cornerRadius = (theImageView.frame.size.height)/2
    theImageView.clipsToBounds = true

要么

theImageView.layer.masksToBounds = true

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

//theImageView.contentMode = .scaleAspectFit
  1. 确保图像视图的宽度和高度相同

21
投票

这应该工作

cell.previewImage.clipsToBounds = YES;

cell.previewImage.layer.cornerRadius = 20;

11
投票

我相信你需要设置:

cell.previewImage.layer.masksToBounds = YES;
cell.previewImage.layer.opaque = NO;

4
投票

在Xcode Interface Builder中,为视图选择“剪辑子视图”绘图属性,同时在代码cell.previewImage.layer.cornerRadius = 20;does中设置角半径,为我完成工作!

See 'Clip Subviews' option in IB


2
投票

试试下面这段代码

cell.previewImage.layer.cornerRadius = 20;
cell.previewImage.clipsToBounds = YES;

1
投票

试试这个代码: -

self.imgaviewName.clipsToBounds = true
self.imageviewName.layer.cornerRadius = 10

0
投票
-(void) viewDidAppear:(BOOL)animated{
       [super viewDidAppear:animated];
       [self setMaskTo:viewDistance 
             byRoundingCorners:UIRectCornerBottomLeft | UIRectCornerBottomRight];
           }

- (void)setMaskTo:(UIView*)view byRoundingCorners:(UIRectCorner)corners
     {
      UIBezierPath *rounded = [UIBezierPath 
                bezierPathWithRoundedRect:view.bounds
                                              byRoundingCorners:corners

                     cornerRadii:CGSizeMake(20.0, 20.0)];

          CAShapeLayer *shape = [[CAShapeLayer alloc] init];
          shape.frame = self.view.bounds;
         [shape setPath:rounded.CGPath];
          view.layer.mask = shape;
       }

0
投票

Swift 4.2答案:

为了使角半径起作用,将图像添加到UIView,然后您需要将图像的masksToBounds属性设置为true

planeImage.layer.masksToBounds = true
planeImage.layer.cornerRadius = 20

注意:用所需的cornerRadius替换20

© www.soinside.com 2019 - 2024. All rights reserved.