Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to compensate the flipped coordinate system of core graphics for easy drawing?

It's really a pain, but always when I draw an UIImage in -drawRect:, it's upside-down.

When I flip the coordinates, the image draws correctly, but at the cost of all other CG functions drawing "wrong" (flipped).

What's your strategy when you have to draw images and other things? Is there any rule of thumb how to not get stuck in this problem over and over again?

Also, one nasty thing when I flip the y-axis is, that my CGRect from the UIImageView frame is wrong. Instead of the origin appearing at 10,10 upper left as expected, it appears at the bottom.

But at the same time, all those normal line drawing functions of CGContext take correct coordinates. drawing a line in -drawRect with origin 10,10 upper left, will really start at upper left. But at the same time that's strange, because core graphics actually has a flipped coordinate system with y 0 at the bottom.

So it seems like something is really inconsistent there. Drawing with CGContext functions takes coordinates as "expected" (cmon, nobody thinks in coordinates starting from bottom left, that's silly), while drawing any kind of image still works the "wrong" way.

Do you use helper methods to draw images? Or is there anything useful that makes image drawing not a pain in the butt?

like image 835
dontWatchMyProfile Avatar asked Apr 22 '10 23:04

dontWatchMyProfile


1 Answers

Problem: Origin is at lower-left corner; positive y goes upward (negative y goes downward).
Goal: Origin at upper-left corner; positive y going downward (negative y going upward).

Solution:

  1. Move origin up by the view's height.
  2. Negate (multiply by -1) the y axis.

The way to do this in code is to translate up by the view bounds' height and scale by (1, -1), in that order.

There are a couple of portions of the Quartz 2D Programming Guide that are relevant to this topic, including “Drawing to a Graphics Context on iPhone OS” and the whole chapter on Transforms. Of course, you really should read the whole thing.

like image 121
Peter Hosey Avatar answered Oct 02 '22 14:10

Peter Hosey