1. 程式人生 > >macOS 開發 - 使用 ScreenSaverView 製作螢幕保護程式

macOS 開發 - 使用 ScreenSaverView 製作螢幕保護程式

文章目錄


製作一個圖片旋轉的螢幕保護程式

參考demo 來源/下載地址:
https://github.com/xiezi222/ScreenSaverDemo


1、建立一個 screensaver project

在這裡插入圖片描述


在這裡插入圖片描述

這裡的 organization name 將作為相關檔案的字首


產生的工程結構如下:
其中會自動產生一個類繼承自 ScreenSaverView, .m 檔案中有 ScreenSaverView 中重要的方法,提供重寫

在這裡插入圖片描述


2、新增 imgView

重寫 initWithFrame 方法:

- (instancetype)initWithFrame:(NSRect)frame isPreview:(BOOL)isPreview
{
    self = [super initWithFrame:frame isPreview:isPreview];
    if (self) {
        
        self.wantsLayer = YES;
        self.layer.backgroundColor = [NSColor cyanColor].CGColor; //無效
        [self setAnimationTimeInterval:1/30.0];
        
        [self setupView0];
        
    }
    return self;
}


- (void)setupView0{
    
    
    NSBundle *bundle = [NSBundle bundleWithIdentifier:@"com.netease.MSSceenSaver"];
    //    NSBundle *bundle = [NSBundle mainBundle]; //使用這個無效
    NSString *imgPath = [bundle pathForResource:@"beauty" ofType:@"png"];
    NSImage *img = [[NSImage alloc] initWithContentsOfFile:imgPath];
    
    CGFloat imgW = 500;
    CGFloat imgH = 500;
    
    CGRect rect = self.bounds;
    
    CGRect fRect = CGRectMake((rect.size.width-imgW)/2, (rect.size.height-imgH)/2, imgW, imgH);
    
    
    self.imgView = [[NSImageView alloc] initWithFrame:fRect];
    [self.imgView setWantsLayer:YES];
    self.imgView.layer.backgroundColor = [NSColor yellowColor].CGColor;
    
    self.imgView.image = img;
    [self addSubview:self.imgView];
}

3、新增imgView 的動畫效果

重寫 animateOneFrame 方法:

你也可以在這個方法中使用貝塞爾曲線等,繪製更多的動畫效果。動畫的頻率由 AnimationTimeInterval 決定。

- (void)animateOneFrame
{
    CALayer *layer = self.imgView.layer;
    
    CATransform3D transfrom = CATransform3DIdentity;
    _angle = _angle - M_PI/200.0;
    if (_angle == -M_PI *2) {
        _angle = 0;
        NSLog(@"_angle reset");
    }
    CGPoint point = CGPointMake(0.5, 0.5);
    transfrom = CATransform3DRotate(transfrom, _angle , 0.0f, 0.0f, 1.0f);
    transfrom = CATransform3DConcat(transfrom, CATransform3DTranslate(CATransform3DIdentity, self.imgView.bounds.size.width/2, self.imgView.bounds.size.height/2, 0));
    layer.anchorPoint = point;
    layer.transform = transfrom;
    return;
}

4、新增到 系統偏好設定 - 桌面與螢幕保護程式

執行程式,將在 product 資料夾中產生一個 .saver 型別檔案。
進入資料夾,雙擊這個 .saver 檔案,系統將提示你安裝。
選擇為此使用者安裝,將安裝到 ~/library/screen savers/ 目錄;
為這臺電腦上所有使用者安裝,將安裝到 /library/screen savers/ 目錄;且安裝和刪除都需要密碼;

在這裡插入圖片描述


在這裡插入圖片描述在這裡插入圖片描述


5、刪除 螢幕保護

在偏好設定面板刪除後,上述資料夾的檔案也會隨之刪除。
在資料夾刪除後,偏好設定中不會馬上刪除,會顯示為預設的屏保;僅退出桌面與保護程式目錄也沒用;需要重啟偏好設定應用。
所以建議除錯有問題時,刪除檔案後,重啟偏好設定。


.saver 檔案

一些系統的螢幕保護程式 會存放在 /system/library/screen savers/ 這個地址;
使用finder 前往去看看,右鍵選中一個 saver 檔案,顯示包內容,可以發現和平時使用的 App 差不多

在這裡插入圖片描述


他的 info.plist 資訊如下:

在這裡插入圖片描述


參考資料