views:

1262

answers:

3

Hi,

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;
}
+1  A: 

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

Ben Gottlieb
Thanks, I thought that would be the best way. Do you know of any good tutorials on using subclasses? Could I use this method with interface builder or should I rewrite my interface in code?
Jack
Actually, Martinj's answer above is probably easier, saving you from having to use a custom subclass everywhere, in Interface Builder, etc.
calmh
+2  A: 

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.

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

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

Martinj
Excellent. Thanks a lot, I'll implement a UIImage category - the tutorial over at macdevelopertips.com is very helpful.
Jack
I was going to describe how to subclass but I like this approach much more.
Kendall Helmstetter Gelner
+6  A: 

Check this - [Previous question on this][1]

[1]: http://stackoverflow.com/questions/205431/rounded-corners-on-uiimage SO UIImage Qn on this

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];
NP Compete
Thanks. This is essentially what I have already done, however I have used the dot notation to change the properties. I was just wondering if there was an easy was to add this to a subclass so that if I wanted to change the radius I wouldn't have to change every instance of this.
Jack