UI-UIImageView的图片填充方式(contentMode)_图片作为控件背景图的拉伸方式(stretch)介绍

常用图片填充方式

  • 这里只介绍三个最常用的图片填充方式
    • UIViewContentModeScaleToFill模式会导致图片变形。例如:

    • UIViewContentModeScaleAspectFit会保证图片比例不变,而且全部显示在ImageView中,这意味着ImageView会有部分空白。例如:

    • UIViewContentModeScaleAspectFill也会证图片比例不变,但是是填充整个ImageView的,可能只有部分图片显示出来。例如:


图片作为控件背景图的拉伸方式

  • 当一个图片作为一个控件的背景图时,并且图片的尺寸< 控件的尺寸.则需要进行拉伸.而普通的以上三种模式达不到预期效果,首先看未拉伸以前效果:运行以后超级难看

  • 进行拉伸以后的效果

  • 拉伸代码:

  • 其中stretchableImageWithLeftCapWidth这个方法是让程序员确定从哪个位置进行拉伸,此代码中填写的是图片高度的二分之一,宽度的二分之一,也就是中心点的位置向外进行平铺,则图片可以达到整个控件.以达到效果.

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    // 加载背景图片
    UIImage *normal = [UIImage imageNamed:@"RedButton"];
    UIImage *highlighted = [UIImage imageNamed:@"RedButtonPressed"];
    
    // 设置图片的拉伸方式
    normal = [normal stretchableImageWithLeftCapWidth:normal.size.width * 0.5 topCapHeight:normal.size.height * 0.5];
    highlighted = [highlighted stretchableImageWithLeftCapWidth:highlighted.size.width * 0.5 topCapHeight:highlighted.size.height * 0.5];
    
    // 把图设置给按钮
    [self.loginButton setBackgroundImage:normal forState:UIControlStateNormal];
    [self.loginButton setBackgroundImage:highlighted forState:UIControlStateHighlighted];
}


  • 拉伸原理图:画的不好见谅.
  • 除了四个角其他位置全部是由中心点平铺而来.
原文地址:https://www.cnblogs.com/adampei-bobo/p/5313866.html