UIEdgeInsets ignored on CGContextDrawImage within a UIGraphicsBeginImageContextWithOptions

亡梦爱人 提交于 2020-01-11 06:00:26

问题


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):

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):

.

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:


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)];


来源:https://stackoverflow.com/questions/12562742/uiedgeinsets-ignored-on-cgcontextdrawimage-within-a-uigraphicsbeginimagecontextw

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!