iOS 图片拉伸技巧

作者: 阳关三叠 | 来源:发表于2015-10-18 20:37 被阅读2086次

    在项目中有的图片需要拉伸处理(比如QQ聊天信息的Message Button背景图片),常用的有两种方式:

    一. 参考李明杰博客:iOS图片拉伸技巧

    iOS中提供很好用的API帮我们实现上述功能。到iOS 6.0为止,iOS提供了3种图片拉伸的解决方案,接下来分别详细介绍这些方案。
    <pre>

    • (UIImage *)stretchableImageWithLeftCapWidth:(NSInteger)leftCapWidth topCapHeight:(NSInteger)topCapHeight;
    • (UIImage *)resizableImageWithCapInsets:(UIEdgeInsets)capInsets;
    • (UIImage *)resizableImageWithCapInsets:(UIEdgeInsets)capInsets resizingMode:(UIImageResizingMode)resizingMode;
      </pre>
      1、iOS 5.0之前
      iOS中有个叫端盖(end cap)的概念,用来指定图片中的哪一部分不用拉伸。比如下图中,黑色代表需要被拉伸的矩形区域,上下左右不需要被拉伸的边缘就称为端盖。
    拉伸部分

    <pre>

    • (UIImage *)resizableImageWithName:(NSString *)name
      {
      UIImage *normal = [UIImage imageNamed:name];
      // 左端盖宽度
      NSInteger leftCapWidth = normal.size.width * 0.5f;
      // 顶端盖高度
      NSInteger topCapHeight = normal.size.height * 0.5f;
      // 重新赋值
      return [normal stretchableImageWithLeftCapWidth:leftCapWidth topCapHeight:topCapHeight];
      }
      </pre>

    2、iOS 5.0
    <pre>+ (UIImage *)resizableImageWithName:(NSString *)name
    {
    UIImage *normal = [UIImage imageNamed:name];
    CGFloat w = normal.size.width * 0.5;
    CGFloat h = normal.size.height * 0.5;
    return [normal resizableImageWithCapInsets:UIEdgeInsetsMake(h, w, h, w)];
    }</pre>
    3、iOS 6.0
    对比iOS5.0中的方法,只多了一个UIImageResizingMode参数,用来指定拉伸的模式:
    UIImageResizingModeStretch:拉伸模式,通过拉伸UIEdgeInsets指定的矩形区域来填充图片
    UIImageResizingModeTile:平铺模式,通过重复显示UIEdgeInsets指定的矩形区域来填充图片

    二. 在xcode中设置图片的Slices

    949324-b3661340dfc36003.png

    Top,Bottom,Height是Xcode默认设置的最优参数,可以根据需要实际调整。
    点击Slices后可以看到:

    949324-83229d58bab4ade7.png

    Tiles:填充
    Stretches:拉伸
    直接按右下角的 Show Slicing可以很直观的设置具体拉伸那个部位

    相关文章

      网友评论

      本文标题:iOS 图片拉伸技巧

      本文链接:https://www.haomeiwen.com/subject/xrvacttx.html