This is because you're not drawing a closed path properly. You're just drawing 4 separate lines.
Try this...
// all your setup code...
[path moveToPoint:x1];
[path addLineToPoint:x2];
[path addLineToPoint:y2];
[path addLineToPoint:y1];
[path addLineToPoint:x1];
[path closePath];
[path fill];
[path stroke];
This should work.
A bit of explanation
From the docs the closePath
method...
Closes the current subpath by creating a line segment between the first and last points of the current subpath.
moveToPoint
will start a new subPath within the current path.
This is used thusly...
Move to P1. Path = 0.
Add line to P2. Path = P1-P2.
Add line to P3. Path = P1-P2-P3.
Close path. Path = P1-P2-P3(-P1).
What you are doing is...
Move to P1. Path = 0.
Add line to P2. Path = P1-P2.
Move to P2. Path = P1-P2.
Add line to P3. Path = P1-P2 | P2-P3.
Move to P3. Path = P1-P2 | P2-P3.
Add line to P1. Path = P1-P2 | P2-P3 | P3-P1.
Close path. Path = P1-P2 | P2-P3 | P3-P1(-P3).
All you have closed is the last line subpath. Moving to a point will start a new subpath in the path.