What is UIViewContentMode

UIViewContentMode

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

舉例來說要將原圖(512x512)放入280x160的顯示區塊

原圖

不同的 ContentMode 會有不同的效果,說明如下:

  • ScaleToFill: 比例會跑掉。
  • ScaleAspectFit: 維持比例放入整張圖,周圍會留白。
  • ScaleAspectFill: 維持比例置中放入圖片,多餘的部份會被卡掉。
  • ScaleAspectFill+AlignTopLeft: 維持圖片比例,但要置上,也就是卡掉下方多餘的部份。

ScaleAspectFill+AlignTopLeft 實作如下:

UIImage *uiimage = [UIImage imageNamed:@"origin.png"];
// 設定顯示區塊
UIImageView *uiimageview = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 280, 160)];
uiimageview.contentMode = UIViewContentModeTopLeft;
// 卡掉多餘的部份
uiimageview.clipsToBounds = YES;
// resize image to 280x280
uiimageview.image = [self resizeImage:uiimage imageSize:CGSizeMake(280, 280) ];

Read more about ContentMode.