我以编程方式设置带边框的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];
Run Code Online (Sandbox Code Playgroud)
显然,我希望黑色边框可以根据纵横比调整,并在所有面上环绕图像.相反它保留在原始框架中,看起来像这样:
Ian*_*n L 19
使用从弗兰克施密特在稍微修改的方法此篇,可以添加的方法制定出显示缩放到方面的图像所需的帧:
- (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);
}
Run Code Online (Sandbox Code Playgroud)
然后,您可以在设置UIImageView图像后调用它:
CGRect frame = [self getFrameSizeForImage:imageView.image inImageView:imageView];
Run Code Online (Sandbox Code Playgroud)
最后,使用此框架设置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;
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
3766 次 |
最近记录: |