Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 4539142
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 21, 20262026-05-21T14:54:21+00:00 2026-05-21T14:54:21+00:00

In a Cocoa-based App i’m having a canvas for drawing, inherited from NSView, as

  • 0

In a Cocoa-based App i’m having a canvas for drawing, inherited from NSView, as well as a rectangle, also inherited from NSView. Dragging the rectangle around inside of the canvas is no problem:

-(void)mouseDragged:(NSEvent *)theEvent {
  NSPoint myOrigin = self.frame.origin;

  [self setFrameOrigin:NSMakePoint(myOrigin.x + [theEvent deltaX], 
                                   myOrigin.y - [theEvent deltaY])];
}

Works like a charm. The issue i’m having now: How can i prevent the rectangle from being moved outside the canvas?

So, first of all i would like to fix this just for the left border, adapting the other edges afterwards. My first idea is: “check whether the x-origin of the rectangle is negative”. But: once it is negative the rectangle can’t be moved anymore around (naturally). I solved this with moving the rectangle to zero x-offset in the else-branch. This works but it’s … ugly.

So i’m little puzzled with this one, any hints? Definitely the solution is really near and easy. That easy, that i cannot figure it out (as always with easy solutions ;).

Regards

Macs

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-21T14:54:22+00:00Added an answer on May 21, 2026 at 2:54 pm

    I’d suggest not using the deltaX and deltaY; try using the event’s location in the superview. You’ll need a reference to the subview.

    // In the superview
    - (void)mouseDragged:(NSEvent *)event {
        NSPoint mousePoint = [self convertPoint:[event locationInWindow] 
                                 fromView:nil];
    
        // Could also add the width of the moving rectangle to this check 
        // to keep any part of it from going outside the superview
        mousePoint.x = MAX(0, MIN(mousePoint.x, self.bounds.size.width));
        mousePoint.y = MAX(0, MIN(mousePoint.y, self.bounds.size.height));
    
        // position is a custom ivar that indicates the center of the object;
        // you could also use frame.origin, but it looks nicer if objects are 
        // dragged from their centers
        myMovingRectangle.position = mousePoint;
        [self setNeedsDisplay:YES];
    }
    

    You’d do essentially the same bounds checking in mouseUp:.

    UPDATE: You should also have a look at the View Programming Guide, which walks you through creating a draggable view: Creating a Custom View.


    Sample code that should be helpful, though not strictly relevant to your original question:

    In DotView.m:

    - (void)drawRect:(NSRect)dirtyRect {
        // Ignoring dirtyRect for simplicity
        [[NSColor colorWithDeviceRed:0.85 green:0.8 blue:0.8 alpha:1] set];
        NSRectFill([self bounds]);
        // Dot is the custom shape class that can draw itself; see below
        // dots is an NSMutableArray containing the shapes
        for (Dot *dot in dots) {
            [dot draw];
        }
    }
    
    - (void)mouseDown:(NSEvent *)event {
        NSPoint mousePoint = [self convertPoint:[event locationInWindow] 
                                 fromView:nil];
    
        currMovingDot = [self clickedDotForPoint:mousePoint];
        // Move the dot to the point to indicate that the user has
        // successfully "grabbed" it    
        if( currMovingDot ) currMovingDot.position = mousePoint;
        [self setNeedsDisplay:YES];
    }
    
    // -mouseDragged: already defined earlier in post
    
    - (void)mouseUp:(NSEvent *)event {
        if( !currMovingDot ) return;
    
        NSPoint mousePoint = [self convertPoint:[event locationInWindow] 
                                 fromView:nil];
        spot.x = MAX(0, MIN(mousePoint.x, self.bounds.size.width));
        spot.y = MAX(0, MIN(mousePoint.y, self.bounds.size.height));
    
        currMovingDot.position = mousePoint;
        currMovingDot = nil;
        [self setNeedsDisplay:YES];
    }
    
    - (Dot *)clickedDotForPoint:(NSPoint)point {
        // DOT_NUCLEUS_RADIUS is the size of the 
        // dot's internal "handle"
        for( Dot *dot in dots ){
            if( (abs(dot.position.x - point.x) <= DOT_NUCLEUS_RADIUS) &&
                (abs(dot.position.y - point.y) <= DOT_NUCLEUS_RADIUS)) {
                return dot;
            }
        }
        return nil;
    }
    

    Dot.h

    #define DOT_NUCLEUS_RADIUS (5)
    
    @interface Dot : NSObject {
        NSPoint position;
    }
    
    @property (assign) NSPoint position;
    
    - (void)draw;
    
    @end
    

    Dot.m

    #import "Dot.h"
    
    @implementation Dot
    
    @synthesize position;
    
    - (void)draw {
        //!!!: Demo only: assume that focus is locked on a view.
        NSColor *clr = [NSColor colorWithDeviceRed:0.3 
                                             green:0.2 
                                              blue:0.8 
                                             alpha:1];
        // Draw a nice border
        NSBezierPath *outerCirc;
        outerCirc = [NSBezierPath bezierPathWithOvalInRect:
                             NSMakeRect(position.x - 23, position.y - 23, 46, 46)];
        [clr set];
        [outerCirc stroke];
        [[clr colorWithAlphaComponent:0.7] set];
        [outerCirc fill];
        [clr set];
        // Draw the "handle"
        NSRect nucleusRect = NSMakeRect(position.x - DOT_NUCLEUS_RADIUS,
                                        position.y - DOT_NUCLEUS_RADIUS,
                                        DOT_NUCLEUS_RADIUS * 2,
                                        DOT_NUCLEUS_RADIUS * 2);
        [[NSBezierPath bezierPathWithOvalInRect:nucleusRect] fill];
    }
    
    @end
    

    As you can see, the Dot class is very lightweight, and uses bezier paths to draw. The superview can handle the user interaction.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have a document-based Cocoa app. During runtime, I load an additional nib from
Assume I have a Cocoa-based Mac or iOS app. I'd like to run a
Environment: xcode 3.2.1, document-based core-data application. I have a document-based cocoa app which uses
I am developing a document based cocoa app. The startup interface is modeled after
I'm working on a html/javascript + cocoa hybrid app. From what I can tell,
I have created a Cocoa document based picture drawing application. I want that the
Developing iOS5 based cocoa app, below peice of comparison works fine if localization is
I have a simple document-based Cocoa app that acts as a viewer for .wav
1>1st project : I have created a window based cocoa touch app just for
I've got an Objective-C/cocoa based application that I'm working on. This app is client<->server.

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.