本文共 1972 字,大约阅读时间需要 6 分钟。
在macOS桌面上添加一个透明的无边框水印,可以通过创建一个始终位于桌面上但其他窗口之下的窗口实现。以下是 Objective-C 代码示例,展示了如何在桌面上创建一个简单的暗水印。
首先,我们需要创建一个新的 macOS 项目。在 Xcode 中,点击 File > New Project,选择 App 模板,然后点击 Next。在项目信息中,输入项目名称(例如 DesktopWatermark),并选择 Objective-C 语言和 macOS 平台。
接下来,我们需要配置窗口属性,使其无边框、透明,并且不会影响用户操作。打开 AppDelegate.h 文件,将以下代码添加到 AppDelegate 类中:
@property (strong) NSWindow *watermarkWindow;
然后,在 AppDelegate.m 中实现这个属性,并添加窗口创建代码:
@interface AppDelegate ()@property (strong) NSWindow *watermarkWindow;@end@implementation AppDelegate- (void)createWatermarkWindow { self.watermarkWindow = [[NSWindow alloc initWithContentRect:[[NSScreen mainScreen] frame] styleMask:NSWindowStyleMaskTransparent]; // 设置窗口属性 [self.watermarkWindow setOpaque:NO]; [self.watermarkWindow setHasShadow:NO]; [self.watermarkWindow setIsOnTopWindowGroup:NO]; [self.watermarkWindow setLevel:NSWindowLevelStatusBarWindow]; // 创建水印内容 NSView *watermarkView = [[NSTextView alloc init]; [watermarkView setAttributedStringValue:[[NSAttributedString alloc initWithString:@"DESKTOP WATERMARK"]]]; [watermarkView setFontAttributes:[[NSDictionary alloc initWithObject: [[NSFont systemFontWithSize:12]] forKeys: @"NSFontKeyAttribute"]]]; // 将水印添加到窗口 [self.watermarkWindow setContentView:watermarkView]; // 确保窗口始终显示 [self.watermarkWindow setOrderedOutOfOrder:YES]; [self.watermarkWindow orderOut:(NSWindowOrderOutNeverOnTop | NSWindowOrderOutNotHandledBySystem);} 在 AppDelegate 中,确保在应用启动时创建并显示水印窗口。修改 AppDelegate 的 main 函数,或者在 AppDelegate 中添加一个启动时间的方法:
- (void)applicationDidFinishLoading { [self createWatermarkWindow]; [self.watermarkWindow makeKeyWindow];} 在 Xcode 中运行应用程序,确保水印窗口在桌面上显示,并且不影响其他窗口的使用。可以调整水印的位置和大小,通过修改 createWatermarkWindow 方法中的 contentRect 参数。
通过以上步骤,您可以轻松在 macOS 桌面上实现一个透明的暗水印效果。这是 macOS 应用开发中一个基本但实用的技巧,适用于需要隐藏或注明特定区域的场景。
转载地址:http://plnfk.baihongyu.com/