iOS開發技巧-UIImageView 的contentMode屬性說明和使用

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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章