【问题标题】:How do you use an asset catalog image's slicing information programmatically?您如何以编程方式使用资产目录图像的切片信息?
【发布时间】:2014-02-07 07:29:44
【问题描述】:

我曾经在我的项目中有一张图片,我会这样加载它:

UIImage *image = [[UIImage imageNamed:@"image_name"] resizableImageWithCapInsets:UIEdgeInsetsMake(10.0f, 10.0f, 10.0f, 10.0f)];

现在我将该图像放入 XCode 5 的新资产目录中,并为其设置切片。如何在我的代码中使用该图像,以便在加载图像时不必显式调用resizableImageWithCapInsets

换一种说法,我如何获取存储在 Images.xcassets 中的切片信息并将其存储在 UIImagecapInsets 属性中?

还是我认为这一切都错了?

【问题讨论】:

    标签: ios uiimage xcode5 asset-catalog


    【解决方案1】:

    好的,我能解决这个问题。

    为了自动使用存储在资产目录 (Images.xcassets) 中的图像中的切片信息,您需要将部署目标设置为 7.0(或更高版本)。

    希望这对其他人有帮助。

    【讨论】:

      【解决方案2】:

      我与 iOS 6/7 兼容的解决方案是在 Xib 文件中使用用户定义的运行时属性。这样我们就不必在源代码中到处写不雅的行来将 xib 中设置的图像替换为按钮帽插入的可拉伸图像。

      第 1 步:在 Xib 中,选择按钮并在 Identity Inspector 面板中设置用户定义的运行时属性。您可以定义一个属性来设置 cap insets。例如,一个名为“capEnabled”的属性只有一个简单的布尔值来指示我们要为按钮使用默认的 cap insets。 (我打算附上屏幕截图,但我被告知我需要至少 10 个声望才能发布图片...... :-( )

      第 2 步:在 UIButton 上创建一个类别并添加一个属性“capEnabled”并实现 getter 和 setter 方法。

      @interface UIButton (NBAHelper)
      @property (nonatomic, assign) BOOL capEnabled;
      @end
      
      @implementation UIButton (NBAHelper)
      
      -(BOOL)capEnabled{
          UIImage *buttonBackgroundImage = [self backgroundImageForState:UIControlStateNormal];
          CGFloat capLeft = buttonBackgroundImage ? buttonBackgroundImage.capInsets.left : 0;
          return capLeft>0;
      }
      
      -(void)setCapEnabled:(BOOL)capEnabled{
          if (capEnabled) {
              UIImage *buttonBackgroundImage = [self backgroundImageForState:UIControlStateNormal];
              if (buttonBackgroundImage) {
                  [self setBackgroundImage:[buttonBackgroundImage stretchableImageWithLeftCapWidth:5 topCapHeight:5] forState:UIControlStateNormal];
              }
          }
      }
      @end
      

      第三步:在任何你想为你创建的 UIButton 使用新功能的地方导入类别的头文件,或者直接将它导入到 .pch 文件中。

      希望我的解决方案对您有所帮助。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-06-07
        • 1970-01-01
        • 2020-07-09
        • 2015-08-15
        • 1970-01-01
        相关资源
        最近更新 更多