Cocoa: NSRectFill on button click does not work

前端 未结 3 1026
没有蜡笔的小新
没有蜡笔的小新 2020-12-22 00:39

Hello I am new to Cocoa programming and I met a problem about NSRectFill.

There is one button in the window, and the following is my AppDelegate.m file:



        
相关标签:
3条回答
  • 2020-12-22 01:11

    Take a look at apple's Drawing Guide

    0 讨论(0)
  • 2020-12-22 01:18

    well you don't have any context, the system has no idea where you want to draw. if you want to draw on a view or an image you have to use a lockFocus / unlockFocus pair.

    so if you have a view as an outlet called redView

    [redView lockFocus];
    [[NSColor redColor] set];
    NSRectFill(NSMakeRect( 50,50,10,10));
    [redView unlockFocus];
    

    but this is a really poor model, you generally want your objects to draw themselves.

    when a views drawRect: method is called you already have focus and don't need the lock unlock pair

    0 讨论(0)
  • 2020-12-22 01:30

    Some background, applicationDidFinishLaunching: is called at the launch of a program once the program is 'done' loading resources.

    But at this point, there could be many windows and many views displayed by the application. Simply calling NSRectFill() is not enough. The application wouldn't know where to draw said rectangle (is it in this window or that one? This NSView or that one). Even if there's only one window and it might seem obvious... there might be multiple NSViews displayed that you're unaware of.... and with computers you have to be very explicit with your commands.

    The bottom line is: there is no 'context' established for where the drawing actions to occur. As d00dle points out, you should read up on Drawing Guide.

    When an NSView's drawRect: is called, a context (itself) has already been set/defined. You could draw directly from your delegate's applicationDidFinishLaunching: but a 'context' needs to be defined.

    0 讨论(0)
提交回复
热议问题