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?
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;
}
You can subclass UIImageView and then if you implement its setNeedsDisplay method the round corners will work on subclasses. (don't forget to import QuartzCore)
Check this - Rounded Corners on UIImage
The layer modification seems to be the best way.
Yes, you should subclass UIImageView, and use your custom subclass throughout your project.
You could use a category for UIImage which is an alternate way to subclass a Class and sometimes easier for just small changes.
e.g add a method that returns a UIImage with the rounded corner attributes set.
more info on Objective-c categories can be found http://macdevelopertips.com/objective-c/objective-c-categories.html
Rather than subclassing, you can achieve more powerful functionality through simple categories on UIImageView and CALayer.
Create a category on UIImageView like this:
This calls a category method on CALayer:
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 styleUITableView
. There is one caveat when doing this however. Because we've not subclassedUIImageView
, we cannot inject any code intolayoutSubviews
, 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 usingUIRectCornersAllCorners
).Here is some code which does this:
I have another category which removes rounded corners - all that does is remove any masks and set the
cornerRadius
to 0.Try this,
this may help you.