• 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: "Michael Ash" <email@hidden>
  • Date: Fri, 21 Nov 2008 21:44:35 -0500

On Fri, Nov 21, 2008 at 6:33 PM, Greg Titus <email@hidden> wrote:
>
> 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;
> }

You'll want an additional check using the reciprocal slope and the X
intercept, as this code will fail on vertical lines and be very
inaccurate on nearly vertical lines. You'll probably want to do both
and make it an OR check, that is if this check succeeds then return
YES, otherwise do the other case and return YES if it succeeds.

Mike
_______________________________________________

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

References: 
 >CGPoint and CGRect (From: DKJ <email@hidden>)
 >Re: CGPoint and CGRect (From: Greg Titus <email@hidden>)

  • Prev by Date: Re: simple question about variable retain/release (NSDate)
  • Next by Date: More instability in Distributed Objects used between multithreaded processes?
  • Previous by thread: Re: CGPoint and CGRect
  • Next by thread: Objective-C variadic methods vs. NSArray et al.
  • Index(es):
    • Date
    • Thread