我想使用以下代码将内容模式的角半径设置为宽高比:
cell.imgvAlbum.contentMode = UIViewContentModeScaleAspectFit;
cell.imgvAlbum.clipsToBounds = YES;
cell.imgvAlbum.layer.cornerRadius = 5.0f;
但我只是为内容模式获取输出,因为方面适合。 我也尝试过:
cell.imgvAlbum.layer.masksToBounds = YES;
角落半径怎么办? 请给我一些解决方案。提前谢谢。
答案 0 :(得分:4)
使用以下方法获取圆角的指定半径的圆角图像,将上述所有属性应用为UIViewContentModeScaleAspectFit
,剪切到边界e.t.c.在图像视图上,通过在图像视图上调用下面的函数来设置接收的图像。
-(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];
答案 1 :(得分:3)
使用UIViewContentModeScaleAspectFit时,图像并不总是填充ImageView的框架,这就是您无法看到角半径的原因。
尝试将背景颜色添加到imageView,您将看到角半径正在工作。
如果您想在任何情况下查看圆角,您应该使用其他内容模式,例如aspectFill或scaleToFill。 例如:
cell.imgvAlbum.contentMode = UIViewContentModeScaleAspectFill;
另一种选择是增加放在imageView中的图像的大小或减小imageView的大小。
答案 2 :(得分:1)
UIImageView Corner Radius only Top left and Right in iOS
UIBezierPath *maskPath;
maskPath = [UIBezierPath bezierPathWithRoundedRect:imageLayer.bounds
byRoundingCorners:(UIRectCornerTopLeft|UIRectCornerTopRight)
cornerRadii:CGSizeMake(10.0, 10.0)];
CAShapeLayer *maskLayer = [[CAShapeLayer alloc] init];
maskLayer.frame = self.bounds;
maskLayer.path = maskPath.CGPath;
imageLayer.mask = maskLayer;
答案 3 :(得分:0)
快速版本作为扩展实用程序:
extension UIImage {
/**
- Parameter cornerRadius: The radius to round the image to.
- Returns: A new image with the specified `cornerRadius`.
**/
func roundedImage(cornerRadius: CGFloat) -> UIImage? {
let size = self.size
// create image layer
let imageLayer = CALayer()
imageLayer.frame = CGRect(x: 0, y: 0, width: size.width, height: size.height)
imageLayer.contents = self.cgImage
// set radius
imageLayer.masksToBounds = true
imageLayer.cornerRadius = cornerRadius
// get rounded image
UIGraphicsBeginImageContext(size)
if let context = UIGraphicsGetCurrentContext() {
imageLayer.render(in: context)
}
let roundImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return roundImage
}
用法-不要忘记在imageView
上重新设置新图像:
switch self.imageContentMode {
case .scaleAspectFit:
// round actual image if aspect fit
self.image = self.image?.roundedImage(cornerRadius: radius)
self.imageView?.image = self.image
default:
// round image view corners
self.imageView?.roundCorners(radius: radius)
}