UIView的UIViewContentMode的效果

先看一下apple的官方定义:

typedef NS_ENUM(NSInteger, UIViewContentMode) {
    UIViewContentModeScaleToFill,
    UIViewContentModeScaleAspectFit,      // contents scaled to fit with fixed aspect. remainder is transparent
    UIViewContentModeScaleAspectFill,     // contents scaled to fill with fixed aspect. some portion of content may be clipped.
    UIViewContentModeRedraw,              // redraw on bounds change (calls -setNeedsDisplay)
    UIViewContentModeCenter,              // contents remain same size. positioned adjusted.
    UIViewContentModeTop,
    UIViewContentModeBottom,
    UIViewContentModeLeft,
    UIViewContentModeRight,
    UIViewContentModeTopLeft,
    UIViewContentModeTopRight,
    UIViewContentModeBottomLeft,
    UIViewContentModeBottomRight,
};

实验代码

#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor grayColor];
    UIView *bgView = [UIView new];
    bgView.backgroundColor = [UIColor yellowColor];
    bgView.bounds = CGRectMake(0,0,250, 400);
    bgView.center = self.view.center;
    bgView.clipsToBounds = YES;
    [self.view addSubview:bgView];
    
    UIImageView *imv = [UIImageView new];
    imv.backgroundColor = [UIColor blueColor];
    imv.image = [UIImage imageNamed:@"test"];
    imv.frame = CGRectMake(0, 0, 200, 300);
    imv.contentMode  = UIViewContentModeScaleToFill;
    [bgView addSubview:imv];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
    1. UIViewContentModeScaleToFill
      图片进行了缩放、填充满整个ImageView,导致变形
UIView的UIViewContentMode的效果_第1张图片
Paste_Image.png
  • 2.UIViewContentModeScaleAspectFit
    图片不变形的拉伸,直到 h = max(长,宽) 达到最大
UIView的UIViewContentMode的效果_第2张图片
Paste_Image.png
  • 3.UIViewContentModeScaleAspectFill
    图片不变形的拉伸,不留空白的拉伸、直到 h = min(长,者)达到最大
UIView的UIViewContentMode的效果_第3张图片
Paste_Image.png

配合 imv.layer.masksToBounds = YES;属性使用,多余部分被裁剪掉了

UIView的UIViewContentMode的效果_第4张图片
Paste_Image.png

你可能感兴趣的:(UIView的UIViewContentMode的效果)