Reputation: 881
I am trying to get a nice round corner on a UIImageView. I have found an implemented the following code, which works fine if the image is a square. The problem is that my imageView is a rectangular photo, sometimes portrait sometimes landscape. This code is clipping off the corners, but doesn't give a smooth curve when one side of the image is longer than the other. Any Ideas? Also is the float in setCornerRadius applied to the image as a percentage of the sides or just straight pixel count?
// Get the Layer of any view
CALayer * l = [imageView layer];
[l setMasksToBounds:YES];
[l setCornerRadius:100.0];
Here is the fix for all interested.
Okay after some playing with it I figured out I needed to resize the imageView to fit the image. I implemented the following method to set the frame size.
- (CGRect)getScaleForFrameFromImage:(UIImage *)image
{
// get the bigger side of image to determine the shape then
// get the percentage we need to scale to to trim imageViewFrame
// so it fits image and sits in the space dedicated in main view for the image
float percentage;
float newWidth;
float newHeight;
float w = image.size.width;
float h = image.size.height;
if (w > h) {
// landscape
percentage = 280 / w;
newWidth = w * percentage;
newHeight = h * percentage;;
}
else {
percentage = 208 / h;
newWidth = w * percentage;
newHeight = h * percentage;
}
int xOrigin = 20 + (280 - newWidth) / 2;
CGRect newFrame = CGRectMake(xOrigin, 160, newWidth, newHeight);
return newFrame;
}
then in my viewWillAppear I did this
// set the imageFrame size
[imageView setFrame:[self getScaleForFrameFromImage:imageToDisplay]];
// Use that image to put on the screen in imageView
[imageView setImage:imageToDisplay];
// Get the Layer of imageView
CALayer * l = [imageView layer];
[l setMasksToBounds:YES];
[l setCornerRadius:10.0];
Upvotes: 1
Views: 2605
Reputation: 46
What i recommend is to draw the imageView with the size of the image and then apply corner radius.
It would be something like this.
// get the size of the image.
CGSize *size = yourImage.size;
// use the size to set the uiimageview frame
UIImageView * imageView = [UIImageView alloc] initWithFrame:CGRecMake(0,0,size.widht,size.height)];
[imageView setImage:yourImage];
//
CALayer * l = [imageView layer];
[l setMasksToBounds:YES];
[l setCornerRadius:100.0];
Upvotes: 2