iOS: ImageView 方面适合角半径

标签 ios uiimageview uicollectionviewcell

我想使用以下代码将内容模式的角半径设置为纵横比:

  cell.imgvAlbum.contentMode = UIViewContentModeScaleAspectFit;
  cell.imgvAlbum.clipsToBounds = YES;
  cell.imgvAlbum.layer.cornerRadius  = 5.0f;

但我只获得内容模式的输出作为纵横比匹配。 我也尝试过:

  cell.imgvAlbum.layer.masksToBounds  = YES;

圆角半径怎么办? 请给我一些解决方案。提前致谢。

最佳答案

使用以下方法获取具有指定圆角半径的圆角图像,将上述所有属性应用为 UIViewContentModeScaleAspectFit,裁剪到边界等。在 ImageView 上,并通过在 ImageView 上调用以下函数来设置接收到的图像。

-(UIImage *)makeRoundedImage:(UIImage *) image
                      radius: (float) radius;
{
    CALayer *imageLayer = [CALayer layer];
    imageLayer.frame = CGRectMake(0, 0, image.size.width, image.size.height);
    imageLayer.contents = (id) image.CGImage;

    imageLayer.masksToBounds = YES;
    imageLayer.cornerRadius = radius;

    UIGraphicsBeginImageContext(image.size);
    [imageLayer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage *roundedImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    return roundedImage;
}

调用为

  UIImage *image = [self makeRoundedImage:[UIImage imageNamed:@"accept~iphone"]
                    radius: 5.0f];

  cell.imgvAlbum.contentMode = UIViewContentModeScaleAspectFit;
  cell.imgvAlbum.clipsToBounds = YES;
  cell.imgvAlbum.layer.cornerRadius  = 5.0f;

  cell.imgvAlbum.layer.masksToBounds  = YES;

  [cell.imgvAlbum setImage: image];

关于iOS: ImageView 方面适合角半径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30747338/

相关文章:

ios - 在点击 map 注释图钉时执行 segue

ios - Swift iOS - 如何排列子层位置以匹配按钮文本的中心

ios - 如何在UIColor中获得随机的暖色/冷色?

ios - Swift - 带有手势的 UIImageView 子类 - 翻译不工作

ios - 如何在 swift 4 中设置对 collectionView 的关注?

ios - Swift - 在 UICollectionView 中点击时如何使单元格缩小效果(如 ios 12 快捷方式应用程序和 App Store 应用程序)

ios - Swift- 将索引路径数组转换为 Int 数组

ios - 如何让 UIButton 变成一个圆圈?

ios - 如何在 Xcode7 中卡住 swift 应用程序

ios - 自动检测旋转时选择的 Collection View 单元格的中心