Can the size of a stretchable button image be anim

2019-08-15 03:00发布

问题:

I'm creating a UIButton with a stretchableImageWithLeftCapWidth:topCapHeight:

I would like to change it's size smoothly with Core Animation like so:

float shrinkFactor = 0.2;
NSTimeInterval slowSpeed = 5.0;

[UIView beginAnimations:nil context:nil];
[UIView setAnimationDuration:slowSpeed];

UIButton *thisButton = (UIButton *)[self.view viewWithTag:2];
thisButton.frame = CGRectMake(thisButton.frame.origin.x, thisButton.frame.origin.y, buttonStretchedWidth * shrinkFactor, thisButton.frame.size.height);

[UIView commitAnimations];

The button image size doesn't animate, it just snaps to the new size.

When I make the backgroundColor of the button visible, I see the frame itself animates correctly.

Am I missing something or is the image stretching not animatable?

回答1:

I've never been able to get image stretching to update continuously. Try splitting your image up into the caps and center areas and create eight or nine UIImageView subviews with the appropriate autoresizingMask set. E.g. the top-right corner view should have UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleBottomMargin, the bottom-center view (getting stretched) should have UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin, and so on. Views are pretty cheap on the iPhone OS, once they're created, so I don't think you'll see a performance hit unless you're animating a half-dozen buttons at once. Make sure to make whatever you can opaque, though—compositing non-opaque views is pretty expensive.