gpt4 book ai didi

objective-c - 如何在非正方形 Objective C UIImageView 上获得平滑的圆角半径

转载 作者:行者123 更新时间:2023-11-29 11:15:06 25 4
gpt4 key购买 nike

我想在 UIImageView 上获得一个漂亮的圆角。我找到了一个实现了以下代码,如果图像是正方形,它可以正常工作。问题是我的 imageView 是一张矩形照片,有时是纵向的,有时是横向的。这段代码剪掉了角落,但当图像的一侧比另一侧长时,不会给出平滑的曲线。有任何想法吗? setCornerRadius 中的 float 是作为边的百分比还是只是直线像素数应用于图像?

    // 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];

关于objective-c - 如何在非正方形 Objective C UIImageView 上获得平滑的圆角半径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9824450/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com