Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

renderInContext flips the origin of colorWithPatternImage

Tags:

ios

I have UIView with backgroundColor set with colorWithPatternImage. As expected, the background image is drawn starting at the top left corner.

Problem appears when I'm doing renderInContext on that view: the background image is drawn starting at the bottom left corner. Everything else seems to render fine.

Here's the source and destination images:

enter image description here

Here is the code:

// here is the layer to be rendered into an image
UIView *src = [[UIView alloc] initWithFrame:(CGRect){{0, 0}, {100, 100}}];
src.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"background.png"]];
[self.view addSubview:src];

// here we'll display the image
UIImageView *dest = [[UIImageView alloc] initWithFrame:(CGRect){{110, 0}, src.bounds.size}];
[self.view addSubview:dest];

// render `src` to an image in `dest`
UIGraphicsBeginImageContext(src.bounds.size);
CGContextRef context = UIGraphicsGetCurrentContext();
[src.layer renderInContext:context];
dest.image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

Is there a way to keep the image to tile in right direction, as in the src view?

like image 538
5lava Avatar asked Nov 18 '12 23:11

5lava


2 Answers

I managed to work around this by calling CGContextSetPatternPhase with a height of modf(viewHeight, patternHeight)

like image 70
Costa Ciprian Avatar answered Nov 26 '22 02:11

Costa Ciprian


https://developer.apple.com/library/ios/#documentation/GraphicsImaging/Conceptual/drawingwithquartz2d/dq_overview/dq_overview.html#//apple_ref/doc/uid/TP30001066-CH202-CJBBAEEC

This doc explains why this happens, in particular this part:

Important: The above discussion is essential to understand if you plan to write applications that directly target Quartz on iOS, but it is not sufficient. On iOS 3.2 and later, when UIKit creates a drawing context for your application, it also makes additional changes to the context to match the default UIKIt conventions. In particular, patterns and shadows, which are not affected by the CTM, are adjusted separately so that their conventions match UIKit’s coordinate system. In this case, there is no equivalent mechanism to the CTM that your application can use to change a context created by Quartz to match the behavior for a context provided by UIKit; your application must recognize the what kind of context it is drawing into and adjust its behavior to match the expectations of the context.

like image 44
nbransby Avatar answered Nov 26 '22 02:11

nbransby