Pattern with image: UIKit and Core Graphics
This is fun.
The other day I’ve been working on a project that uses controls with patterned textures. I’ve used the texture on one button, then another, and finally on a different control. When I started the app, for some reason the texture on the different control was backwards.
Have a look. The first button’s background is set as:
[view setBackgroundColor:[UIColor colorWithPatternImage:[UIImage imageNamed:@"some-image.png"]]];
And the second:
[view.layer setBackgroundColor:[UIColor colorWithPatternImage:[UIImage imageNamed:@"some-image.png"]].CGColor];
And here’s how both of these actually look like. The UIKit one represents the “correct” orientation of the background texture.
Notice the difference: in the latter case I’m using the view’s layer to set the background color, and I’m using a CGColor reference for that — where CG stands for Core Graphics. UIKit, of course, uses a coordinate system where (0,0) is at the top left. Not so for Core Graphics:
Some iOS technologies define default coordinate systems whose origin point and orientation differ from those used by UIKit. For example, Core Graphics and OpenGL ES use a coordinate system whose origin lies in the lower-left corner of the view or window and whose y-axis points upward relative to the screen.
If we look at things this way, then the texture in the latter case is positioned exactly right, if we mentally rotate it 90 degrees counter-clockwise.
There’s a function to flip the coordinate system used by Core Graphics for use within UIKit, but it’s usually applied only to the current context, which is not always convenient, as in this case. So bear this in mind every time you deal with Core Graphics within UIKit.