Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UIEdgeInsets ignored on CGContextDrawImage within a UIGraphicsBeginImageContextWithOptions

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 adoImage 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

like image 979
Dirk-Willem van Gulik Avatar asked Dec 12 '22 22:12

Dirk-Willem van Gulik


1 Answers

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)];
like image 178
Robin Summerhill Avatar answered May 30 '23 12:05

Robin Summerhill