4

I am struggling getting Image Insets to work when drawing to an off screen buffer.

Using the resizableImageWithCapInsets: on an UIImage directly setImage: into a button works fine for me:

UIImage * base = [UIImage imageNamed:@"button.png"];
UIImage * img = [base resizableImageWithCapInsets:UIEdgeInsetsMake(20,20,20,20)];
[self setImage:img forState:UIControlStateNormal];

As shown below (left is raw scaling, right is scaled with insets):

Image stretched without ado Image stretched with decent insets

So the right one is fine - the lines top/botton/left/right are equally spaced. So far so good.

Now if I try the very same thing with an image that is drawn and then captured to an off screen buffer with:

UIImage * base = [UIImage imageNamed:@"button.png"];
base = [base resizableImageWithCapInsets:UIEdgeInsetsMake(20,20,20,20)];

UIGraphicsBeginImageContextWithOptions(self.bounds.size, NO, 0);
ctx = UIGraphicsGetCurrentContext();

CGContextDrawImage(ctx, CGRectMake(0,0,self.bounds.size.width,
         self.bounds.size.height), [base CGImage]);

img = UIGraphicsGetImageFromCurrentImageContext();

UIGraphicsEndImageContext(); 
[self setImage:img forState:UIControlStateNormal];

I get below (again left is raw scaling, right is with insets):

raw scaling, side bufferscaling with inset, side buffer (WRONG!).

So here it seems that the insets are ignored.

Anyone any suggestions as to what is going wrong here ? Fully functional example at http://people.apache.org/~dirkx/insetSample.zip and just the key code at http://pastebin.com/rm8h6YFV.

Any and all suggestions appreciated.

Dw

1 Answer 1

13

I would guess that stretchable UIImages are handled at a higher level than Quartz2D and so using CGContextDrawImage is not going to work.

You could try using -[UIImage drawInRect] instead. This will draw to the current UIGraphics context, which is your bitmap context that you create in your code snippet.

The relevant line is:

[base drawInRect:CGRectMake(0,0,self.bounds.size.width,
                                    self.bounds.size.height)];
Sign up to request clarification or add additional context in comments.

3 Comments

I just tried editing the project you supplied and making this change fixes your problem.
Thank you - that is indeed spot on. Works lovely with that change (for future reference - pastebin.com/FjZkfb9z is the updated file/code.
Actually - when doing this with the real image (which is sort of an illumated button as seen on vision mixers (flickr.com/photos/peterprice/121342192) - one needs to make sure things are rotated - as the two drawing layers have the Y origin at top resp. bottom.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.