CGRectGetWidth vs CGRect.size.width
Asked Answered
N

2

30

Which is better to use? I prefer CGRect.size.width cause it looks nicer. But, my colleague says CGRectGetWidth is better.

Nastassia answered 11/5, 2011 at 21:25 Comment(0)
G
21

CGRectGetWidth/Height will normalize the width or height before returning them. Normalization is basically just checking if the width or height is negative, and negating it to make it positive if so.

Answered here

Globulin answered 11/5, 2011 at 21:28 Comment(5)
How could width or height ever be negative?Nastassia
I have no idea. It doesn't make sense to me either but it's the only answer I know of. I use CGRect structures, like you do, myself and have never had an issue. You should challenge your colleague to show you an instance where it matters and then post that answer back here!Globulin
FYI I think they put the origin (0,0) in the centre, so the left and top edges are often negative, but the right and bottom edges are positive.Radiator
developer.apple.com/library/mac/#documentation/graphicsimaging/… offers some explanation of negative values. "For this reason, your applications should avoid directly reading and writing the data stored in the CGRect data structure."Eth
developer.apple.com/documentation/coregraphics/cggeometry, this is the working link!Happ
E
12

A rect's width and height can be negative. I have no idea when this would be true in practice, but according to Apple docs:

CGGeometry Reference defines structures for geometric primitives and functions that operate on them. The data structure CGPoint represents a point in a two-dimensional coordinate system. The data structure CGRect represents the location and dimensions of a rectangle. The data structure CGSize represents the dimensions of width and height.

The height and width stored in a CGRect data structure can be negative. For example, a rectangle with an origin of [0.0, 0.0] and a size of [10.0,10.0] is exactly equivalent to a rectangle with an origin of [10.0, 10.0] and a size of [-10.0,-10.0]. Your application can standardize a rectangle—that is, ensure that the height and width are stored as positive values—by calling the CGRectStandardize function. All functions described in this reference that take CGRect data structures as inputs implicitly standardize those rectangles before calculating their results. For this reason, your applications should avoid directly reading and writing the data stored in the CGRect data structure. Instead, use the functions described here to manipulate rectangles and to retrieve their characteristics.

Estradiol answered 27/5, 2014 at 22:14 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.