• Open Menu Close Menu
  • Apple
  • Shopping Bag
  • Apple
  • Mac
  • iPad
  • iPhone
  • Watch
  • TV
  • Music
  • Support
  • Search apple.com
  • Shopping Bag

Lists

Open Menu Close Menu
  • Terms and Conditions
  • Lists hosted on this site
  • Email the Postmaster
  • Tips for posting to public mailing lists
Re: CGPoint and CGRect
[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: CGPoint and CGRect


  • Subject: Re: CGPoint and CGRect
  • From: Greg Titus <email@hidden>
  • Date: Fri, 21 Nov 2008 15:33:02 -0800


On Nov 21, 2008, at 3:19 PM, DKJ wrote:

I want to determine whether a line between two CGPoints in a view intersects with a given CGRect. There's nothing in the CGGeometry reference that does this specifically, and I don't yet see how to use the functions that are there to figure this out.

Before I dust off my Euclid (a rare first edition), has anyone got a quick solution? It seems the sort of thing that would be handy in many situations.

dkj

BOOL lineIntersectsRect(CGPoint a, CGPoint b, CGRect rect) { float lineSlope = (b.y - a.y) / (b.x - a.x); float yIntercept = a.y - lineSlope * a.x; float leftY = lineSlope * NSMinX(rect) + yIntercept; float rightY = lineSlope * NSMaxX(rect) + yIntercept;

	if (leftY >= NSMinY(rect) && leftY <= NSMaxY(rect))
		return YES;
	if (rightY >= NSMinY(rect) && rightY <= NSMaxY(rect))
		return YES;
	return NO;
}

Here's something I just wrote in email (so may be totally wrong), but basically you determine the slope and y-intercept of the line formed by the two points, then see where that line's Y-position would be on each of the left and right sides of the rectangle. If the Y-position hits the left or right edges of the rect, then the line intersects the rect.

Note that this is line intersection, not line _segment_ intersection. If the line doesn't extend beyond the two points given, you'll need a couple extra checks in this code.

Hope this helps,
	- Greg
_______________________________________________

Cocoa-dev mailing list (email@hidden)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden


  • Follow-Ups:
    • Re: CGPoint and CGRect
      • From: "Michael Ash" <email@hidden>
References: 
 >CGPoint and CGRect (From: DKJ <email@hidden>)

  • Prev by Date: CGPoint and CGRect
  • Next by Date: Objective-C variadic methods vs. NSArray et al.
  • Previous by thread: CGPoint and CGRect
  • Next by thread: Re: CGPoint and CGRect
  • Index(es):
    • Date
    • Thread