【问题标题】:unable to set the image view to be circle无法将图像视图设置为圆形
【发布时间】:2014-03-16 06:57:51
【问题描述】:

我需要制作头像图片圈(类似于whats app) 我使用的单元格是 UITableViewCellStyleDefault

这是我的代码:

    User *user = [DBHelper fetchUserWithUserID:userID];
    cell.imageView.image = [Helper imageWithBlob:user.profile.thumbnailPhotoBlob defaultImageFile:FILE_DEFAULT_PHOTO];
    cell.imageView.layer.cornerRadius = cell.imageView.frame.size.height /2;
    cell.imageView.clipsToBounds = YES;
    cell.imageView.layer.masksToBounds = YES;

但结果图像视图仍然是正方形

编辑:图像视图的框架是 {0, 0, 0, 0},但它确实显示了图像。

编辑2:

我尝试了答案,但图像不是圆形。这是我所做的:

float height = [self tableView:tableView heightForRowAtIndexPath:indexPath];
[Helper circlizeImageView:cell.imageView cellHeihgt:height];


+ (void)circlizeImageView:(UIImageView *)imageView cellHeihgt:(float)cellHeight {
    imageView.frame = CGRectMake(0, 0, cellHeight, cellHeight);
    [Helper circlizeView:imageView];
}
+ (void)circlizeView:(UIView *)view {
    view.layer.cornerRadius = view.frame.size.height / 2;
    view.clipsToBounds = YES;
    view.layer.masksToBounds = YES;
}

【问题讨论】:

  • 我导入了整个
  • 我试过 QuartzCore/CoreAnimation.h 也不工作
  • 您是否尝试将图像视图作为子视图添加到单元格内容视图中?
  • 不,但是默认单元格已经带有图像视图
  • 我编辑了问题

标签: ios uitableview uiimageview uikit


【解决方案1】:

代码一切正常。

唯一的问题是这一行:

cell.imageView.layer.cornerRadius = cell.imageView.frame.size.height/2;
//CGRect rectTest = cell.imageView.frame;
//returns a rect of (0,0,0,0) & hence the cornerRadius being set is 0.

试试:

cell.imageView.layer.cornerRadius = 10; //or some fixed value

回想起来,您尝试做的事情不会让您将imageView 设为圆形,因为默认的imageView 是矩形(高度总是大于宽度),所以...设置一个角半径是高度/宽度的一半将不起作用。

如果你使用自定义UITableViewCell并添加一个方形框架imageView会更好。

无论如何...由于默认imageView 触及默认UITableViewCell 的顶部并在底部结束,因此您可以通过使用行的高度来获得imageView 的高度(如果您有动态大小的单元格)

那么,就这么简单:

cell.imageView.layer.cornerRadius = cell.frame.size.height/2;

但这一切看起来都不是很好,因为imageView 是矩形的,并且单元格的动态高度会使它看起来像一个糟糕的设计(固定半径看起来最好恕我直言)

【讨论】:

  • ic,我只是传入 heightForRow 作为半径,因为 imageView 的框架仅在您分配图像后设置
  • @OMGPOP :imageView 的框架似乎在分配图像后设置了很多。所以......即使heightForRow 也不会在所有情况下都有效。事实上,关键是您不能确保每个单元格的imageview 都是循环的,因为您无法访问imageView 的框架。您最好使用 custom UITableViewCell。但是...如果您确定您的图像将始终为 30 像素 x 30 像素,您可以将cornerRadius 设置为 15 并保持不变。
【解决方案2】:

你有两个选择:

1- 将imageView 作为subView 添加到您的单元格中。

2- 在自定义单元格中覆盖 layoutSubviews

- (void)layoutSubviews {
    [super layoutSubviews];
    self.imageView.frame = CGRectMake(0,0,40,40);
}

【讨论】:

  • 是的,尝试将大小传递给单元格,cell.imageSize = mySize; //imageSize是你cell类中的一个属性,根据这个size设置imageView的frame。
  • 我没有单元格类。我在代码中注册了重用标识符并直接使用系统单元格。
  • 好的,然后将您的单元格子类化,但上面的layoutSubviews 在.m 中,我建议以任何方式将imageView 添加为子视图,这是更好的做法。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-03-23
  • 1970-01-01
  • 2020-02-09
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多