stretchableImageWithLeftCapWidth:topCapHeight does

2019-07-03 17:07发布

问题:

I have a UIImageView subclass called ShadowView, which displays a shadow that can be used under anything. ShadowViews are to be loaded from a nib.

In initWithCoder:, I have the following code:

- (id)initWithCoder:(NSCoder *)decoder {
    self = [super initWithCoder:decoder];
    if (self != nil) {
        UIImage *shadowImage = [[UIImage imageNamed:@"drop_shadow_4_pix.png"] stretchableImageWithLeftCapWidth:4 topCapHeight:4];

        [self setContentMode:UIViewContentModeScaleToFill];
        [self setImage:shadowImage];
    }
    return self;
}

When I run the app, though, this image does not appear.

But if I change it to

...
UIImage *shadowImage = [UIImage imageNamed:@"drop_shadow_4_pix.png"];
...

it works fine, but it is stretched wrong.

Any ideas as to why this is happening?

Edit: it is the same when I load the shadowview programmatically, with initWithFrame: implemented similarly to initWithCoder:.

Another Edit: I think I solved the problem. I needed to set the autoresizing masks.

回答1:

Is shadowImage nil?

UIImage *shadowImage = [[UIImage imageNamed:@"drop_shadow_4_pix.png"] stretchableImageWithLeftCapWidth:4 topCapHeight:4];

That method could return nil if the base image is less than 5 pixels wide or 5 pixels tall since it needs the 4 pixels for the caps + 1 pixel to stretch.