2010-11-30 125 views
94

我有点遗憾。我已经使用UIView的图层属性四舍五入在我的应用程序中的多个元素的角落。但是,这一个UIImageView根本不符合。不知道我错过了什么。在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. 
} 

有没有关于我错过的单元格加载的方式?

回答

317

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

cell.previewImage.layer.masksToBounds = YES;

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

+12

当心这个将会是一个巨大的业绩冲击 – jjxtra 2012-08-31 23:12:23

+5

为什么这是一个性能问题? – Michael 2013-04-28 15:01:05

+0

@PsychoDad为什么? – 2013-08-12 13:00:11

11

我相信你需要设置:

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

这应该工作

cell.previewImage.clipsToBounds = YES; 

cell.previewImage.layer.cornerRadius = 20; 
3

在Xcode中Interface Builder中,选择“剪辑子视图”的观点图纸属性连同设置拐角半径代码cell.previewImage.layer.cornerRadius = 20;为我工作!

See 'Clip Subviews' option in IB

2

试试这个下面的代码

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

另外值得一提的是,

  1. 如果您正在使用aspectFit和cornerRadius与clipsToBounds/masksToBounds,你不会得到圆角。如果你有这样的

    theImageView.contentMode = .scaleAspectFit 
    

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

    theImageView.layer.masksToBounds = true 
    

    行不通

即。你将不得不摆脱aspectFit代码

//theImageView.contentMode = .scaleAspectFit 
  • 确保宽度和图像视图高度相同
  • 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; 
         }