我想在UIImageView上获得一个漂亮的圆角。我发现实现了以下代码,如果图像是正方形,它可以正常工作。问题是我的imageView是一张矩形照片,有时候肖像有时是风景照片。此代码剪切了角落,但是当图像的一侧比另一侧长时,不会给出平滑的曲线。有任何想法吗? setCornerRadius中的浮点数是应用于图像的百分比还是直接像素数?
// Get the Layer of any view
CALayer * l = [imageView layer];
[l setMasksToBounds:YES];
[l setCornerRadius:100.0];
这是所有感兴趣的解决方案。
好吧,在玩了一些之后我发现我需要调整imageView的大小以适应图像。我实现了以下方法来设置帧大小。
- (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;
}
然后在我的视图中,我做了这个
// 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];
答案 0 :(得分:2)
我建议使用图像大小绘制imageView,然后应用圆角半径。
会是这样的。
// 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];