iOS开发技巧-UIImageView 的contentMode属性说明和使用

版权声明:本文为博主原创文章,未经博主允许不得转载。[email protected] 技术讨论群:536739494 https://blog.csdn.net/Nathan1987_/article/details/81136369

contentMode这个属性是用来设置图片的显示方式,如居中、居右,是否缩放等。
苹果api里面的说明

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,
};

测试代码

- (void)viewDidLoad
{
    [super viewDidLoad];

    [self.view addSubview:self.picIMV];
    CGFloat x,y,w,h;
    x = 100;
    y = 100;
    w = 200;
    h = 200;
    CGRect r_rect = (CGRect){x,y,w,h};
    self.picIMV.frame = r_rect;
    self.picIMV.image = [UIImage imageNamed:@"yui01.jpeg"];
    self.picIMV.center = self.view.center;
}

- (UIImageView *)picIMV
{
    if (!_picIMV)
    {
        _picIMV = [[UIImageView alloc]init];
        _picIMV.contentMode = UIViewContentModeScaleAspectFill;
        _picIMV.backgroundColor = [UIColor redColor];
    }
    return _picIMV;
}

没有带Scale的,当图片尺寸超过 ImageView尺寸时,只有部分显示在ImageView中。
UIViewContentModeScaleToFill 属性会导致图片变形
UIViewContentModeScaleAspectFit 会保证图片比例不变,而且全部显示在ImageView中,这意味着ImageView会有部分空白。
UIViewContentModeScaleAspectFill也会证图片比例不变,但是是填充整个ImageView的,可能只有部分图片显示出来。

UIViewContentModeScaleToFill例子:
图片是变形了的,和ImageView比例不同
UIViewContentModeScaleToFill效果.png

UIViewContentModeScaleAspectFit例子:
红色是ImageView的背景颜色,比例和图比例不同,导致出现ImageView空白

UIViewContentModeScaleAspectFit效果图.png

UIViewContentModeScaleAspectFill例子:
图片超出了ImageView的范围
UIViewContentModeScaleAspectFill效果.png

设置clipsToBounds = YES 后,会裁剪掉超出ImageView的范围的图片
clipsToBounds设置YES.png

猜你喜欢

转载自blog.csdn.net/Nathan1987_/article/details/81136369