浅说UIView 的几种填充模式

历史版本

版本号 时间
V1.0 2017.07.12

前言

大家在做图片上传还有头像等很多时候,经常都会碰到图片拉伸或者压缩等几种情况,下面我们就举个例子说一下这几种填充模式。

一、代码展示

  下面我们就先写一个简单的控件,并渲染出来如下所示。

先看一下下面的代码。

#import "JJContentModeVC.h"

@interface JJContentModeVC ()

@property (nonatomic, strong) UIImageView *coverImageView;

@end

@implementation JJContentModeVC

#pragma mark - Override Base Function

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    self.view.backgroundColor = [UIColor whiteColor];
    
    [self setupUI];
}

#pragma mark - Object Private Function

- (void)setupUI
{
    UIImageView *coverImageView = [[UIImageView alloc] init];
    coverImageView.image = [UIImage imageNamed:@"girl_or_women"];
    coverImageView.frame = CGRectMake(50.0, 300.0, 200, 200.0);
    [self.view addSubview:coverImageView];
    self.coverImageView = coverImageView;
}

@end

下面我们先看一下原图

原图展示

下面看一下仿真器效果图。

模拟器

二、几种内容模式基础

下面我们看一下苹果的API,如下所示。

@interface UIView(UIViewRendering)

- (void)drawRect:(CGRect)rect;

- (void)setNeedsDisplay;
- (void)setNeedsDisplayInRect:(CGRect)rect;

@property(nonatomic)                 BOOL              clipsToBounds;              // When YES, content and subviews are clipped to the bounds of the view. Default is NO.
@property(nullable, nonatomic,copy)            UIColor          *backgroundColor UI_APPEARANCE_SELECTOR; // default is nil. Can be useful with the appearance proxy on custom UIView subclasses.
@property(nonatomic)                 CGFloat           alpha;                      // animatable. default is 1.0
@property(nonatomic,getter=isOpaque) BOOL              opaque;                     // default is YES. opaque views must fill their entire bounds or the results are undefined. the active CGContext in drawRect: will not have been cleared and may have non-zeroed pixels
@property(nonatomic)                 BOOL              clearsContextBeforeDrawing; // default is YES. ignored for opaque views. for non-opaque views causes the active CGContext in drawRect: to be pre-filled with transparent pixels
@property(nonatomic,getter=isHidden) BOOL              hidden;                     // default is NO. doesn't check superviews
@property(nonatomic)                 UIViewContentMode contentMode;                // default is UIViewContentModeScaleToFill
@property(nonatomic)                 CGRect            contentStretch NS_DEPRECATED_IOS(3_0,6_0) __TVOS_PROHIBITED; // animatable. default is unit rectangle {{0,0} {1,1}}. Now deprecated: please use -[UIImage resizableImageWithCapInsets:] to achieve the same effect.

@property(nullable, nonatomic,strong)          UIView           *maskView NS_AVAILABLE_IOS(8_0);

/*
 -tintColor always returns a color. The color returned is the first non-default value in the receiver's superview chain (starting with itself).
 If no non-default value is found, a system-defined color is returned.
 If this view's -tintAdjustmentMode returns Dimmed, then the color that is returned for -tintColor will automatically be dimmed.
 If your view subclass uses tintColor in its rendering, override -tintColorDidChange in order to refresh the rendering if the color changes.
 */
@property(null_resettable, nonatomic, strong) UIColor *tintColor NS_AVAILABLE_IOS(7_0);

/*
 -tintAdjustmentMode always returns either UIViewTintAdjustmentModeNormal or UIViewTintAdjustmentModeDimmed. The value returned is the first non-default value in the receiver's superview chain (starting with itself).
 If no non-default value is found, UIViewTintAdjustmentModeNormal is returned.
 When tintAdjustmentMode has a value of UIViewTintAdjustmentModeDimmed for a view, the color it returns from tintColor will be modified to give a dimmed appearance.
 When the tintAdjustmentMode of a view changes (either the view's value changing or by one of its superview's values changing), -tintColorDidChange will be called to allow the view to refresh its rendering.
 */
@property(nonatomic) UIViewTintAdjustmentMode tintAdjustmentMode NS_AVAILABLE_IOS(7_0);

/*
 The -tintColorDidChange message is sent to appropriate subviews of a view when its tintColor is changed by client code or to subviews in the view hierarchy of a view whose tintColor is implicitly changed when its superview or tintAdjustmentMode changes.
 */
- (void)tintColorDidChange NS_AVAILABLE_IOS(7_0);

@end

   contentMode是UIView的属性,这个属性的值决定了,当视图的几何形状变化时如何复用它的内容。当视图第一次展示前,它会将自己的内容渲染成一张底层的bitmap。 然后视图的几何变化都不会使bitmap重新生成。而视图contentMode属性的值决定了bitmap是否缩放、位置在哪儿(固定在左边、右边、上面、下面、居中)。它是UIView的子类UIViewRendering的一个属性,它是以一个枚举值,默认是UIViewContentModeScaleToFill。

下面看一下这个枚举值。

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


三、几种填充模式讲解和效果展示

下面我们就说一下下面几种模式及其效果展示。

1. UIViewContentModeScaleToFill

这个是填充模式的默认选项。

UIViewContentModeScaleToFill

Scales the content to fit the size of itself by changing the aspect ratio of the content if necessary.
改变内容的高宽比例,缩放内容,UIView中完整显示内容,填满UIView,

  上面那个模拟器图就是这个内容模式下的效果,imageView的尺寸没有改变,这里改变的是所给图像的宽高比例,并且全部填充到UIImageView里面。下面看代码和效果。

- (void)setupUI
{
    UIImageView *coverImageView = [[UIImageView alloc] init];
    coverImageView.contentMode = UIViewContentModeScaleToFill;
    coverImageView.clipsToBounds = YES;
    coverImageView.layer.borderColor = [UIColor blueColor].CGColor;
    coverImageView.layer.borderWidth = 0.5;
    coverImageView.image = [UIImage imageNamed:@"girl_or_women"];
    coverImageView.frame = CGRectMake(50.0, 300.0, 200, 200.0);
    [self.view addSubview:coverImageView];
    self.coverImageView = coverImageView;
}

效果展示如下所示。

效果1

2. UIViewContentModeScaleAspectFit

UIViewContentModeScaleAspectFit

 Scales the content to fit the size of the view by maintaining the aspect ratio. Any remaining area of the view’s bounds is transparent.
保持内容的高宽比,缩放内容,完整显示内容,最大化填充UIview,没填充上的区域透明

下面我们看一下代码和效果。

- (void)setupUI
{
    UIImageView *coverImageView = [[UIImageView alloc] init];
    coverImageView.contentMode = UIViewContentModeScaleAspectFit;
    coverImageView.clipsToBounds = YES;
    coverImageView.layer.borderColor = [UIColor blueColor].CGColor;
    coverImageView.layer.borderWidth = 0.5;
    coverImageView.image = [UIImage imageNamed:@"girl_or_women"];
    coverImageView.frame = CGRectMake(50.0, 300.0, 200, 200.0);
    [self.view addSubview:coverImageView];
    self.coverImageView = coverImageView;
}

效果2

3. UIViewContentModeScaleAspectFill

UIViewContentModeScaleAspectFill

Scales the content to fill the size of the view. Some portion of the content may be clipped to fill the view’s bounds.
保持内容高宽比,缩放内容,超出视图的部分内容会被裁减,填充UIView

下面看一下效果图和代码。

- (void)setupUI
{
    UIImageView *coverImageView = [[UIImageView alloc] init];
    coverImageView.contentMode = UIViewContentModeScaleAspectFill;
    coverImageView.clipsToBounds = YES;
    coverImageView.layer.borderColor = [UIColor blueColor].CGColor;
    coverImageView.layer.borderWidth = 0.5;
    coverImageView.image = [UIImage imageNamed:@"girl_or_women"];
    coverImageView.frame = CGRectMake(50.0, 300.0, 200, 200.0);
    [self.view addSubview:coverImageView];
    self.coverImageView = coverImageView;
}
效果3

  这个方法严格按照图像的宽高比进行填充,超过的部分会被裁剪掉,好处就是这个方法保证不会失真,可以看见右边的纸盒子已经被裁剪掉了。

4. UIViewContentModeRedraw

UIViewContentModeRedraw

The option to redisplay the view when the bounds change by invoking the setNeedsDisplay method.
当View的bounds改变,系统会调用setNeedsDisplay,重新绘制视图

下面看代码和效果。

- (void)setupUI
{
    UIImageView *coverImageView = [[UIImageView alloc] init];
    coverImageView.contentMode = UIViewContentModeRedraw;
    coverImageView.clipsToBounds = YES;
    coverImageView.layer.borderColor = [UIColor blueColor].CGColor;
    coverImageView.layer.borderWidth = 0.5;
    coverImageView.image = [UIImage imageNamed:@"girl_or_women"];
    coverImageView.frame = CGRectMake(50.0, 300.0, 200, 200.0);
    [self.view addSubview:coverImageView];
    self.coverImageView = coverImageView;
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        coverImageView.frame = CGRectMake(50.0, 300.0, 220, 130.0);
    });
}

  我这里采用了延时处理,3s后更改imageview的bounds,系统会自动调用setNeedsDisplay方法,重新绘制,效果如下图所示。

效果4

5. UIViewContentModeCenter

UIViewContentModeCenter

The option to center the content in the view’s bounds, keeping the proportions the same.
不缩放,内容在视图中间

下面我们就看一下代码和效果。

- (void)setupUI
{
    UIImageView *coverImageView = [[UIImageView alloc] init];
    coverImageView.contentMode = UIViewContentModeCenter;
    coverImageView.clipsToBounds = YES;
    coverImageView.layer.borderColor = [UIColor blueColor].CGColor;
    coverImageView.layer.borderWidth = 0.5;
    coverImageView.image = [UIImage imageNamed:@"girl_or_women"];
    coverImageView.frame = CGRectMake(50.0, 300.0, 200, 200.0);
    [self.view addSubview:coverImageView];
    self.coverImageView = coverImageView;
}

下面看效果图。

效果5

6. UIViewContentModeTop

UIViewContentModeTop

不缩放,内容在视图上部。

下面看一下代码和效果。

- (void)setupUI
{
    UIImageView *coverImageView = [[UIImageView alloc] init];
    coverImageView.contentMode = UIViewContentModeTop;
    coverImageView.clipsToBounds = YES;
    coverImageView.layer.borderColor = [UIColor blueColor].CGColor;
    coverImageView.layer.borderWidth = 0.5;
    coverImageView.image = [UIImage imageNamed:@"girl_or_women"];
    coverImageView.frame = CGRectMake(50.0, 300.0, 200, 200.0);
    [self.view addSubview:coverImageView];
    self.coverImageView = coverImageView;
}
效果6

  剩下的其他几种方法很不常用而且简单易懂这里就不说了。借用网络上的一张图片让大家看看,所有填充模式的填充效果如下。

展示图1
展示图2

  这里大家可能会有个需求,如果我需要进行一个图像固定区域的裁剪,该如何进行呢,下面给大家一个方法,如下所示。


+ (UIImage *)clipWithClipImage:(UIImage *)clipImage;

{
    float width = clipImage.size.width > clipImage.size.height ? clipImage.size.height : clipImage.size.width;
    CGSize clipSize = CGSizeMake(width, width);
    UIGraphicsBeginImageContext(clipSize);
    [clipImage drawInRect:CGRectMake(0,0,width,width)];
    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return  newImage;    
}

  上面这个方法可以在任意点开始截取,并且截取任意size大小的图片。

后记

  未完,待续~~~~

美女
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 204,921评论 6 478
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 87,635评论 2 381
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 151,393评论 0 338
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,836评论 1 277
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,833评论 5 368
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,685评论 1 281
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 38,043评论 3 399
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,694评论 0 258
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 42,671评论 1 300
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,670评论 2 321
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,779评论 1 332
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,424评论 4 321
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 39,027评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,984评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,214评论 1 260
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 45,108评论 2 351
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,517评论 2 343

推荐阅读更多精彩内容