Search code examples
ioscgrectcgsize

Difference between CGSize and CGRect


What is the difference between CGSize and CGRect?

As a beginner reading the CGGeometry Reference it wasn't immediately obvious, especially because there were references to size being a vector. I was kind of surprised that I couldn't find this basic question on StackOverflow, so I decided to research it more and post my answer below.


Solution

  • CGSize

    CGSize is a width and a height. It is not technically considered a rectangle (which is one reason I confused it with CGRect in the beginning), but rather just a size. However, for the purpose of illustration, I will represent it as a rectangle below:

    enter image description here

    This combination of width and heigh is known as a struct, which is short for structure, and originally comes from the C language (but I will be using the Swift rather than Objective C syntax here). A structure is just a group of logically related variables. Here we can see the CGSize structure:

    struct CGSize {
      var width: CGFloat
      var height: CGFloat
    }
    

    where CGFloat is either a float (32 bit) or a double (64 bit). (See What's the difference between using CGFloat and float?)

    You can make a CGSize by doing the following:

    var size = CGSize(width: 50, height: 30)
    

    CGRect

    CGRect is a rectangle. What is not immediately obvious from the name, though, is that in addition to a width and a height, it also has has an origin.

    enter image description here

    CGsize, by comparison, does not have an origin.

    CGRect is also a structure. If fact, it's a structure of structures: a CGPoint (the origin) and CGSize (the width and height). Here it is:

    struct CGRect {
      var origin: CGPoint
      var size: CGSize
    }
    

    where CGPoint is

    struct CGPoint {
      var x: CGFloat
      var y: CGFloat
    }
    

    You can make a CGRect by doing the following:

    var rect = CGRect(origin: CGPoint(x: 0, y: 0), size: CGSize(width: 50, height: 30))
    

    Negative width and height

    The width and height values can be negative. We can see what this looks like with CGRect. Notice how the origin appears on different corners:

    enter image description here

    Vectors

    The documentation for CGSize says

    A CGSize structure is sometimes used to represent a distance vector, rather than a physical size. As a vector, its values can be negative. To normalize a CGRect structure so that its size is represented by positive values, call the CGRectStandardize function.

    Vectors in math have a magnitude (or length) and a direction. Although CGSize doesn't have an origin, you can see from the following diagram how the width and height along with their associated positive or negative values give both the length and direction.

    enter image description here

    Further Reading