问题
I'm trying to create a "grip" for a vertical bar in my app, to show the user that they can swipe on the view. I'd like to just use a small version of the image, which has the grip and 1 px above and below it which is the background for the rest of the bar. So:
ssss ssss
gggg becomes ssss
ssss gggg
ssss
ssss
The method resizableImageWithCapInsets: allows you to tell iOS not adjust the outside edge, but is there a way to tell it to not adjust the interior and stretch with the exterior?
I've tried specifying a oversized cap inset, UIEdgeInsetsMake(29.0f, 0.0f, 29.0f, 0.0f) and that resulted in the grip being at the top of the image's frame, but otherwise is the correct stretching behavior I'm looking for. I just need to have the grip part centered in the frame.
Full code for those interested (this results in the grip being repeated across the whole length):
gripBar = [[UIImageView alloc] initWithImage:[[UIImage imageNamed:@"grip"] resizableImageWithCapInsets:UIEdgeInsetsMake(1.0f, 0.0f, 1.0f, 0.0f)]];
gripBar.frame = CGRectMake(0, 0, gripWidth, fullHeight);
[view gripBar];
Update: working code based on chosen answer
@implementation GripBar
- (id)init {
self = [super init];
if (self) {
UIImageView *bar = [[UIImageView alloc] initWithImage:[[UIImage imageNamed:@"gripback"] resizableImageWithCapInsets:UIEdgeInsetsMake(0.0f, 0.0f, 1.0f, 0.0f)]];
bar.autoresizingMask = UIViewAutoresizingFlexibleHeight;
[self addSubview:bar];
UIImageView *grip = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"grip"]];
grip.contentMode = UIViewContentModeCenter;
grip.autoresizingMask = UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin;
[self addSubview:grip];
}
return self;
}
@end
回答1:
The easiest way to do this is probably to make your grip part be a (small-height, but full-width) subview of a larger bar view whose background stretches or tiles. You can keep the grip part centered in your larger view by, for example, autoresize masks.
来源:https://stackoverflow.com/questions/11217935/resizable-uiimage-where-outside-stretches-and-inside-is-kept-the-same