How do you use an asset catalog image's slicin

2019-05-03 17:22发布

I used to have an image in my project and I would load it like this:

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

Now I put that image into XCode 5's new asset catalog and I set the slicing for it. How do I use that image in my code so that I don't have to explicitly call resizableImageWithCapInsets when loading the image?

Said another way, how do I take the slicing information stored in Images.xcassets and store it in a UIImage's capInsets property?

Or am I thinking about this all wrong?

2条回答
做自己的国王
2楼-- · 2019-05-03 17:50

Ok, I was able to figure this out.

In order to automatically use the slicing information in an image stored in the asset catalog (Images.xcassets) you need to set your Deployment Target to 7.0 (or higher).

Hope this helps someone else out there.

查看更多
再贱就再见
3楼-- · 2019-05-03 18:01

My solution compatible with iOS 6/7 is using User Defined Runtime Attributes in Xib files. So that we don't have to write inelegant lines everywhere in the source code to replace the image set in xib with stretchable image with cap insets for the button.

Step 1: In Xib, select the button and set the User Defined Runtime Attributes in the Identity Inspector panel. You can define an attribute for setting the cap insets. For example, an attribute called "capEnabled" with just a simple boolean value to indicate we want to use default cap insets for the button. (I intended to attach screenshots but I was told I need at least 10 reputation to post image... :-( )

Step 2: Create a category on UIButton and add a property "capEnabled" and implement the getter and setter methods.

@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

Step3: Import the header file of the category everywhere you want to use the new feature for the UIButton you created or simply import it into the .pch file.

Hope my solution is helpful to you.

查看更多
登录 后发表回答