我正在以编程方式设置带边框的图像视图。我将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];
显然,我希望黑色边框可以根据纵横比调整,并在四周环绕图像。相反它保留在原始框架中,看起来像这样:
答案 0 :(得分:18)
在this post中使用Frank Schmitt略微修改的方法,您可以添加一个方法来计算显示缩放到方面的图像所需的帧:
- (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;
答案 1 :(得分:3)
我完成这项工作的最快方式:
然后在代码中,我将背景图像帧调整为略大于前景图像:
float kBorderSize=5.0;
CGRect imageRect=AVMakeRectWithAspectRatioInsideRect(imageView.image.size,imageView.frame);
CGRect borderRect=CGRectMake(imageRect.origin.x-kBorderSize, imageRect.origin.y-kBorderSize, imageRect.size.width+2*kBorderSize, imageRect.size.height+2*kBorderSize);
backgroundImage.frame=borderRect;
需要导入:
#import <AVFoundation/AVUtilities.h>
答案 2 :(得分:0)
该边框位于imageView上,而不是图像上。要解决此问题,您可以将UIImageView的大小调整为与图像大小相同(或者如果缩小,则与图像具有相同的宽高比),或者实际为图像本身添加边框。
中涵盖了这两种情况