如何在非方形上获得光滑的圆角半径Objective C UIImageView
我想在UIImageView上获得一个不错的圆角。我发现一个实现了下面的代码,如果图像是方形的,它可以正常工作。问题是我的imageView是一张长方形的照片,有时候肖像有时候是风景。这段代码削减了角点,但是当图像的一边比另一边长时,不能给出平滑的曲线。有任何想法吗?另外,setCornerRadius中的浮点数应用于图像作为边的百分比还是直线像素数?如何在非方形上获得光滑的圆角半径Objective C UIImageView
// 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;
}
然后在我的viewWillAppear中我这样做
// 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];
我的建议是与图像的尺寸绘制的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];
这实际上是我刚才意识到的。见上面的评论。 UIImageView是在Navigtion/TableView情况下创建为详细视图的视图的一部分。我目前在viewView的viewWillAppear中设置了视图的图像。我需要一种方法来在运行中调整imageView的大小,而不是在初始化期间。我会看看我能否弄清楚,我会尽快回复你。 ;〜) – vichudson1 2012-03-22 15:04:05
解决。谢谢你的帮助。请参阅主文章中的代码以获得修复。 – vichudson1 2012-03-22 16:53:27
你能发表截图吗?我认为cornerRadius属性在矩形视图上正常工作。 (这是一个像素计数顺便说一句,不是一个百分比。) – 2012-03-22 14:45:15
好吧,所以我正在制作截图张贴过程中,我想我看到了问题。当我拍了一张肖像东方照片时,我根本没有找到圆角,但风景正在变得时髦翘曲的角落。我认为它是因为我的UIImage视图的大小足以填充我认为最大的区域,我希望图像占用。它也被设置为填充IB的方面。我认为代码工作正常,只是我的图像很少填充整个视图。所以我想我应该看看@是如何调整视图到当前图像的大小?建议?我可耻仍然是一个新手;〜) – vichudson1 2012-03-22 14:58:33