ios 为所有 UIImageViews 添加圆角

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2171506/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-30 16:50:28  来源:igfitidea点击:

Add rounded corners to all UIImageViews

iossubclasscode-reuseobjective-c-category

提问by Hyman

I would like to add some rounded corners to all of the UIImageViews in my project. I have already got the code working, but am having to apply it to every image; should I subclass UIImageView to add this? If so, can someone give me some pointers as to how to do this?

我想为我的项目中的所有 UIImageViews 添加一些圆角。我已经让代码工作了,但我不得不将它应用到每个图像上;我应该继承 UIImageView 来添加这个吗?如果是这样,有人能给我一些关于如何做到这一点的指示吗?

Here is the code

这是代码

- (void)viewDidLoad {
    [super viewDidLoad];
    NSString *mainpath = [[NSBundle mainBundle] bundlePath];
    welcomeImageView.image = [UIImage imageWithContentsOfFile:[mainpath stringByAppendingString:@"/test.png"]];
    welcomeImageView.layer.cornerRadius = 9.0;
    welcomeImageView.layer.masksToBounds = YES;
    welcomeImageView.layer.borderColor = [UIColor blackColor].CGColor;
    welcomeImageView.layer.borderWidth = 3.0;
    CGRect frame = welcomeImageView.frame;
    frame.size.width = 100;
    frame.size.height = 100;
    welcomeImageView.frame = frame;
}

采纳答案by Martinj

You could use a category for UIImage which is an alternate way to subclass a Class and sometimes easier for just small changes.

您可以为 UIImage 使用一个类别,这是对 Class 进行子类化的另一种方法,有时更容易进行小的更改。

e.g add a method that returns a UIImage with the rounded corner attributes set.

例如添加一个返回带有圆角属性集的 UIImage 的方法。

+(UIImage *)imageWithContentsOfFile:(NSString *)file cornerRadius:(NSInteger)... 

more info on Objective-c categories can be found http://macdevelopertips.com/objective-c/objective-c-categories.html

有关 Objective-c 类别的更多信息,请访问http://macdevelopertips.com/objective-c/objective-c-categories.html

回答by NP Compete

Check this - Rounded Corners on UIImage

检查这个 - UIImage 上的圆角

The layer modification seems to be the best way.

图层修改似乎是最好的方法。

UIImageView * roundedView = [[UIImageView alloc] initWithImage: [UIImage imageNamed:@"wood.jpg"]];
// Get the Layer of any view
CALayer * l = [roundedView layer];
[l setMasksToBounds:YES];
[l setCornerRadius:10.0];

回答by Daniel Thorpe

Rather than subclassing, you can achieve more powerful functionality through simple categories on UIImageView and CALayer.

您可以通过 UIImageView 和 CALayer 上的简单类别实现更强大的功能,而不是子类化。

Create a category on UIImageView like this:

在 UIImageView 上创建一个类别,如下所示:

- (void)maskRoundCorners:(UIRectCorner)corners radius:(CGFloat)radius {
    // To round all corners, we can just set the radius on the layer
    if ( corners == UIRectCornerAllCorners ) {
        self.layer.cornerRadius = radius;
        self.layer.masksToBounds = YES;
    } else {
        // If we want to choose which corners we want to mask then
        // it is necessary to create a mask layer.
        self.layer.mask = [CALayer maskLayerWithCorners:corners radii:CGSizeMake(radius, radius) frame:self.bounds];
    }
}

This calls a category method on CALayer:

这将调用 CALayer 上的类别方法:

+ (id)maskLayerWithCorners:(UIRectCorner)corners radii:(CGSize)radii frame:(CGRect)frame {

    // Create a CAShapeLayer
    CAShapeLayer *mask = [CAShapeLayer layer];

    // Set the frame
    mask.frame = frame;

    // Set the CGPath from a UIBezierPath
    mask.path = [UIBezierPath bezierPathWithRoundedRect:mask.bounds byRoundingCorners:corners cornerRadii:radii].CGPath;

    // Set the fill color
    mask.fillColor = [UIColor whiteColor].CGColor;

    return mask;
}

So, this allows you to round any combination (see UIRectCorner) of corners, which is especially handy if you want to put an image in a group style UITableView. There is one caveat when doing this however. Because we've not subclassed UIImageView, we cannot inject any code into layoutSubviews, which means that the mask layer may not be correct. In fact, when configuring cells, the bounds of the image view won't even be set when you call the category method. Hence, you need to ensure the bounds of the image view is set before adding rounded corners (except if using UIRectCornersAllCorners).

因此,这允许您对UIRectCorner角的任意组合(参见)进行圆角处理,如果您想将图像置于组样式中,这将特别方便UITableView。但是,在执行此操作时有一个警告。因为我们没有子类化UIImageView,所以我们不能向 注入任何代码layoutSubviews,这意味着掩码层可能不正确。事实上,在配置cell的时候,调用category方法的时候,image view的bounds甚至都不会被设置。因此,您需要确保在添加圆角之前设置图像视图的边界(除非使用UIRectCornersAllCorners)。

Here is some code which does this:

这是一些执行此操作的代码:

        // Perform corner rounding
        UIRectCorner corners = !UIRectCornerAllCorners;
        if (indexPath.row == 0) 
            corners = UIRectCornerTopLeft;
        if (indexPath.row == numberOfRowsInTheTable)  
            corners |= UIRectCornerBottomLeft;

        if (corners > 0) {
            cell.imageView.bounds = CGRectMake(0.f, 0.f, [self.tableView rowHeight], [self.tableView rowHeight]);
            [cell.imageView maskRoundCorners:corners radius:10.f];
        } else {
            [cell.imageView removeRoundCornersMask];
        }

I have another category which removes rounded corners - all that does is remove any masks and set the cornerRadiusto 0.

我有另一个删除圆角的类别 - 所做的就是删除任何蒙版并将其设置cornerRadius为 0。

回答by Ben Gottlieb

Yes, you should subclass UIImageView, and use your custom subclass throughout your project.

是的,您应该继承 UIImageView,并在整个项目中使用您的自定义子类。

回答by Alexey Linkov

You can subclass UIImageView and then if you implement its setNeedsDisplaymethod the round corners will work on subclasses. (don't forget to import QuartzCore)

您可以继承 UIImageView ,然后如果您实现其setNeedsDisplay方法,圆角将适用于子类。(不要忘记导入 QuartzCore)

-(void)setNeedsDisplay {
    self.layer.cornerRadius = 5;
    self.layer.masksToBounds = YES;
    [self.layer setBorderColor:[[UIColor whiteColor] CGColor]];
    [self.layer setBorderWidth: 2.0];
}

回答by Nithinbemitk

Try this,

尝试这个,

coverImage.image = [UIImage imageWithContentsOfFile:@"coverImage.png"]; 
coverImage.layer.masksToBounds = YES;
coverImage.layer.cornerRadius = 10.0;
coverImage.layer.borderWidth = 1.0;
coverImage.layer.borderColor = [[UIColor brown] CGColor];

this may help you.

这可能对你有帮助。