Drawing a custom window on Mac OS X

http://www.cocoawithlove.com/2008/12/drawing-custom-window-on-mac-os-x.html

Occasionally, you may want a window to look completely different to the standard window styles provided by Apple. This post will show you how to draw a custom window and implement close, resize and drag functionality.

Introduction

In this post, I will present a custom window and frame class that will draw the following window:

roundwindow.png

Clicking and dragging in any part of the frame of this window will drag the window, except the gray square (which operates as a resize thumb) and the close box (which operates in a standard manner).

You can download the complete Xcode 3.1 project for RoundWindow (63kB).

Constructing a transparent window

Making a custom window starts with a transparent window. I will use a custom NSWindow subclass named RoundWindow. The constructor for this subclass looks like this:

- ( id )initWithContentRect:(NSRect)contentRect
    styleMask :(NSUInteger)windowStyle
    backing :(NSBackingStoreType)bufferingType
    defer :( BOOL )deferCreation
{
     self = [ super
        initWithContentRect :contentRect
        styleMask :NSBorderlessWindowMask
        backing :bufferingType
        defer :deferCreation];
     if ( self )
     {
         [ self setOpaque : NO ];
         [ self setBackgroundColor :[ NSColor clearColor ]];
     }
     return self ;
}

The three changes made to the window by this constructor are fairly obvious:

  • NSBorderlessWindowMask (a window without standard window framing)
  • setOpaque:NO (so that any part of the window can be transparent)
  • setBackgroundColor:[NSColor clearColor] (if we do nothing else, this will paint the window transparent)

The result is a transparent, rectangular window. This method can be invoked directly (if creating a window in code). It will also be invoked by the NIB loader when loading the window from a NIB.

Since this window uses the NSBorderlessWindowMask style, we must override thecanBecomeKeyWindow and canBecomeMainWindow methods to return YES. These overrides will allow the window to be the keyboard focus and primary application window respectively.

Space for the window frame

Now that we have a clean, blank slate, we need to draw the frame of the window. The first requirement is some space around the content of the window to draw the frame.

To create this space, we override the content to frame conversion methods:

- (NSRect)contentRectForFrameRect:(NSRect)windowFrame
{
     windowFrame .origin = NSZeroPoint ;
     return NSInsetRect(
         windowFrame, WINDOW_FRAME_PADDING , WINDOW_FRAME_PADDING);
}
 
+ (NSRect)frameRectForContentRect:(NSRect)windowContentRect
    styleMask :(NSUInteger)windowStyle
{
     return NSInsetRect(
         windowContentRect, - WINDOW_FRAME_PADDING , -WINDOW_FRAME_PADDING);
}

This will add WINDOW_FRAME_PADDING (75) pixels border around the content rectangle. Actually, since this is a borderless window, the content view itself will be expanded by 75 pixels on each side. The next part will compensate for this, so the content view will be the expected, non-expanded size.

Creating the window frame

The normal structure of a window on Mac OS X is:

  • NSWindow
    • NSThemeFrame (draws the standard window frame)
      • NSView (the window's contentView)

My first thought was to try replacing the existing theme frame view. However, this quickly proved to be too difficult. This private subclass of NSView handles many quirks associated with view hierarchy, layout and window drawing that I didn't want to implement myself.

Instead, I chose to override the setContentView: and contentView: accessors on the window so that my frame view is always inserted between the theme frame and the contentView:

  • NSWindow
    • NSNextStepFrame (the theme frame for a borderless window)
      • RoundWindowFrameView (the contentView as seen by the NSWindow)
        • NSView (the contentView as seen by other classes)

The setContentView: override on the RoundWindow looks like this:

- ( void )setContentView:( NSView *)aView
{
     if ([childContentView isEqualTo :aView])
     {
         return ;
     }
     
     NSRect bounds = [ self frame ];
     bounds .origin = NSZeroPoint ;
 
     RoundWindowFrameView *frameView = [ super contentView ];
     if (!frameView)
     {
         frameView =
             [[[ RoundWindowFrameView alloc ]
                initWithFrame :bounds]
            autorelease ];
         
         [ super setContentView :frameView];
     }
     
     if (childContentView)
     {
         [childContentView removeFromSuperview ];
     }
     childContentView = aView;
     [childContentView setFrame :[ self contentRectForFrameRect :bounds]];
     [childContentView
        setAutoresizingMask : NSViewWidthSizable | NSViewHeightSizable ];
     [frameView addSubview :childContentView];
}

So this method inserts the RoundWindowFrameView in between the content view and theNSNextStepFrame. The childContentView is an instance variable on our RoundWindow class, used to find this view again later (if we are asked to fetch, replace or resize it).

Creating this disparity between the internal content view (our RoundWindowFrameView) and the external content view (the childContentView) creates some issues. Other NSWindow methods likesetContentSize: will also need to be overridden if they are to behave as expected. These overrides should be relatively straightforward and simple, compared to the work that would have been required to replace the NSNextStepView with our RoundWindowFrameView.

Drawing the frame

We can draw the window frame however we want: it's just a custom NSView. We draw the background of the view with [NSColor clearColor] again. The shadow behind the window is drawn automatically for whatever shape we draw. Any part of the window that is left completely clear will not receive mouse clicks (they will fall through the window).

For my custom window, I add a standard close box. The standard close control can be created using the method:

closeButton = [NSWindow
    standardWindowButton : NSWindowCloseButton forStyleMask :NSTitledWindowMask];

There are two quirks. First: it doesn't update itself when the window becomes/resigns mainWindowstatus (so we must detect this and tell it to redisplay). Second: the mouse "rollover" effect doesn't seem to work (I was unable to address this problem).

Handling window controls

The close button will close the window without us doing anything else. Drag and resize behavior will require work on our part.

Both dragging and resizing the window involve changing its frame. So they can both be done by calling:

[window setFrame :newFrame display : YES animate : NO ];

If we continuously call this method in a focus locked event loop that tracksNSLeftMouseDraggedMask operations, then the updates will happen smoothly as the mouse is dragged.

This event loop looks like this:

while ( YES )
{
     NSEvent *newEvent = [window
        nextEventMatchingMask :( NSLeftMouseDraggedMask | NSLeftMouseUpMask)];
     
     if ([newEvent type ] == NSLeftMouseUp)
     {
         break ;
     }
     
     // Determine the frame changes for the mouse operation and apply...
 
}

The code for determining the frame changes, while straightforward, is a little long to include here but you can look at the mouseDown: method in the RoundWindowFrameView to see how it's done.

Conclusion

You can download the complete Xcode 3.1 project for RoundWindow (63kB).

Drawing a custom window with no behavior is simple but as with other types of custom controls, numerous little behavioral additions may be needed to make it feel truly polished.

As a resizable circular window, the RoundWindow suffers from its fixed 75 by 75 pixel frame width. This is too big for small windows and not enough for large windows to properly enclose the content view in a circle. To properly enclose a rectangular content view in a circular frame, the frame would need a variable width (something I didn't want to set up for this simple post).

A custom window may also want to handle truncation of the title when it gets too long. Other window controls like the toolbar button, toolbar, minimize and zoom buttons and the "unsaved changes" status on the close button are all responsibilities of the window frame that have not been investigated here.

Paramanoir has posted an article that draws a custom window in a different way: by swizzling a new  drawRect: method into the default  NSThemeFrame class at runtime. This has a few advantages ( NSThemeFrame continues to handle the window controls) so you may want to consider that approach as an alternative.
购物商城项目采用PHP+mysql有以及html+css jq以及layer.js datatables bootstorap等插件等开发,采用了MVC模式,建立一个完善的电商系统,通过不同用户的不同需求,进行相应的调配和处理,提高对购买用户进行配置….zip项目工程资源经过严格测试可直接运行成功且功能正常的情况才上传,可轻松复刻,拿到资料包后可轻松复现出一样的项目,本人系统开发经验充足(全领域),有任何使用问题欢迎随时与我联系,我会及时为您解惑,提供帮助。 【资源内容】:包含完整源码+工程文件+说明(如有)等。答辩评审平均分达到96分,放心下载使用!可轻松复现,设计报告也可借鉴此项目,该资源内项目代码都经过测试运行成功,功能ok的情况下才上传的。 【提供帮助】:有任何使用问题欢迎随时与我联系,我会及时解答解惑,提供帮助 【附带帮助】:若还需要相关开发工具、学习资料等,我会提供帮助,提供资料,鼓励学习进步 【项目价值】:可用在相关项目设计中,皆可应用在项目、毕业设计、课程设计、期末/期中/大作业、工程实训、大创等学科竞赛比赛、初期项目立项、学习/练手等方面,可借鉴此优质项目实现复刻,设计报告也可借鉴此项目,也可基于此项目来扩展开发出更多功能 下载后请首先打开README文件(如有),项目工程可直接复现复刻,如果基础还行,也可在此程序基础上进行修改,以实现其它功能。供开源学习/技术交流/学习参考,勿用于商业用途。质量优质,放心下载使用。
Project Title: Analyzing Urban Growth Patterns using ArcGIS Pro Project Description: The aim of this project is to analyze the urban growth patterns of a selected city using ArcGIS Pro, a powerful Geographic Information System (GIS) software. The project will involve the following steps: 1. Data Collection: Collecting relevant spatial data such as satellite imagery, land use data, demographic data, transportation data, and other relevant information from reliable sources. 2. Data Preparation: Cleaning and processing the collected data to make it suitable for analysis. This involves converting data formats, removing duplicates, and georeferencing data. 3. Data Analysis: Using ArcGIS Pro to analyze the urban growth patterns of the selected city. This will include spatial analysis of land use changes, population growth, transportation networks, and other relevant factors. 4. Visualization: Creating maps, charts, and other visual aids to present the results of the analysis. This will help to identify trends, patterns, and areas of concern. 5. Conclusion: Drawing conclusions based on the analysis and presenting recommendations for future urban planning. Expected Deliverables: 1. A detailed report outlining the methodology, data sources, analysis, and conclusions of the project. 2. A set of maps, charts, and other visual aids to present the results of the analysis. 3. A PowerPoint presentation summarizing the key findings of the project. 4. Access to the ArcGIS Pro project files for future reference. Project Timeline: The project is expected to take approximately 4-6 weeks to complete. The timeline will be as follows: Week 1-2: Data Collection and Preparation Week 3-4: Data Analysis Week 5: Visualization and Report Writing Week 6: Finalizing the report and presentation Budget: The budget for this project will depend on the availability and cost of data sources. However, it is estimated to be around $1,000-$2,000 for data acquisition and analysis. The cost of the software license for ArcGIS Pro will also need to be factored in.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值