Calculate the view's center vs. calling [self center]


#1

Hi,

In the drawRect: method the center of the view is calculated instead of asking the view for its center.

Are there circumstances where the CGPoint calculated will be different than the value returned from [self center]?

I also think it is valuable from a learner’s point of view to use the functions in CGGeometry instead of accessing struct members. Example CGRectGetWidth and CGRectGetHeight, CGRectGetMidX, CGRectGetMidY are all useful.

float maxRadius = hypot(bounds.size.width, bounds.size.height) / 2.0;

becomes

CGFloat maxRadius = (CGFloat)(hypot(CGRectGetWidth(bounds), CGRectGetHeight(bounds)) / 2.0);

#2

The center method returns the center of the frame. Within a drawRect: method, you want to be working with the bounds, you don’t care much about the position of the view relative to its superview. Try replacing the code to compute the center of the bounds with [self center] to see what I mean. Looks the same right? Now give the HypnosisView a different frame… like half the size of the screen in the bottom left corner. Now you really see what I mean.

As far as direct member access vs. using the CGGeometry functions: both are totally valid. We prefer direct member access because it is easier to read and maintain for us. Your mileage may vary.


#3

Thank you for clarifying. I dug into the docs and now I understand the significance of views having the responsibility of creating the graphics context.