gpt4 book ai didi

objective-c - 边框不适应 Aspect Fit?

转载 作者:技术小花猫 更新时间:2023-10-29 10:22:50 25 4
gpt4 key购买 nike

我正在以编程方式设置带边框的 ImageView 。我将 imageView 的内容模式设置为 Aspect Fit,这有效,但边框仍然是原来的正方形。

代码:

CGRect imageViewRect = CGRectMake(left, top, 158, 119); 
UIImageView *imageView = [[UIImageView alloc] initWithFrame:imageViewRect];
[imageView setContentMode:UIViewContentModeScaleAspectFit];
[imageView setImage:image];
[imageView.layer setBorderColor:[[UIColor blackColor] CGColor]];
[imageView.layer setBorderWidth:3.0];

显然,我希望黑色边框能够根据宽高比进行调整,并从各个方向包围图像。相反,它保留在原始框架中,看起来像这样:

wHAT IT LOOKS LIKE

最佳答案

使用 Frank Schmitt 在 this post 中略微修改的方法,您可以添加一种方法来计算显示按比例缩放的图像所需的帧:

- (CGRect)getFrameSizeForImage:(UIImage *)image inImageView:(UIImageView *)imageView {

float hfactor = image.size.width / imageView.frame.size.width;
float vfactor = image.size.height / imageView.frame.size.height;

float factor = fmax(hfactor, vfactor);

// Divide the size by the greater of the vertical or horizontal shrinkage factor
float newWidth = image.size.width / factor;
float newHeight = image.size.height / factor;

// Then figure out if you need to offset it to center vertically or horizontally
float leftOffset = (imageView.frame.size.width - newWidth) / 2;
float topOffset = (imageView.frame.size.height - newHeight) / 2;

return CGRectMake(leftOffset, topOffset, newWidth, newHeight);
}

然后您可以在设置 UIImageView 图像后调用它:

CGRect frame = [self getFrameSizeForImage:imageView.image inImageView:imageView]; 

最后,使用此框架设置 UIImageView 的框架,偏移位置以适应宽度/高度的任何变化:

CGRect imageViewFrame = CGRectMake(imageView.frame.origin.x + frame.origin.x, imageView.frame.origin.y + frame.origin.y, frame.size.width, frame.size.height);
imageView.frame = imageViewFrame;

关于objective-c - 边框不适应 Aspect Fit?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9706874/

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