Sketch插件开发入门

插件结构

http://developer.sketchapp.com/introduction/plugin-bundles/

sketch 插件就是脚本的集合。每个脚本定义了一个或者多个命令。这些命令可以拓展sketch的功能。sketch插件以 .sketchplugin结尾,其实就是个文件夹,把后缀删除后可以直接打开。

example.sketchplugin
  Contents/
    Sketch/
      manifest.json
      script.cocoascript
    Resources/
      XXX.png
      XXX.png

manifest.json

这个json文件声明插件的元数据.Sketch会读取这个配置文件的信息,得到command的名字和command对应函数实现.
这文件里面最重要的配置项是Commands和Menu:

Commands

声明一组command的信息。每个command以字典形式存在。

  • script : 实现命令功能的函数所在的脚本
  • handler: 函数名,该函数实现命令的功能。Sketch在调用该函数时,会传入一个context参数,context是个字典,里面包含了很多信息,下文会讲到。如果你的没有指定handler,Sketch会默认是script里的onRun函数
  • shortcut:命令的快捷键
  • name:会显示在Sketch的Plugin 的菜单里
  • identifier:唯一标识,建议用com.xxxx.xxx格式
Menu

Sketch加载插件的时候,会根据它指定的信息,顺序地在菜单栏中显示命令名。

{
  "author" : "rongyan.zry",
  "commands" : [
    {
      "script" : "script.cocoascript",
      "handler" : "setFixedMasks",
      "shortcut" : "option m",
      "name" : "Artboard Mask",
      "identifier" : "com.rongyanzry.layermask"
    },
    {
      "script" : "script.cocoascript",
      "handler" : "onRun",
      "shortcut" : "option s",
      "name" : "Artboard Scale",
      "identifier" : "com.rongyanzry.artboardscale"
    }
  ],
  "menu" : {
    "items" : [
      "com.rongyanzry.layermask",
      "com.rongyanzry.artboardscale"
    ],
    "title" : "Artboard Scale"
  },
  "identifier" : "com.rongyanzry.sketch.9a776995-f790-4048-870b-881639f52bcc",
  "version" : "1.0",
  "description" : "A plugin that helps you to scale artboards and layers",
  "authorEmail" : ".....@gmail.com",
  "name" : "Artboard Scale"
}

语言CocoaScript

入门

This is a bridge that lets you write JavaScript scripts that can call native Objective-C/Cocoa.Using it, you can write the logic of your Plugin in JavaScript, but can call the actual classes and methods that implement Sketch itself when you want to make it do something.

CocoaScript.

在使用中用js调objective-c的方法时,

  • 方法调用 用 ‘.’ 语法
  • 参数都放在‘()’里头
  • oc中被参数分割开的函数名,用 ‘ _ ’连接.
  • 返回值,js统一用var类型 ,js是弱类型

比如: MSPlugin的接口valueForKey:onLayer:
oc:

NSString * value = [command valueForKey:kAutoresizingMask onLayer:currentLayer];

cocoascript:

var value = command.valueForKey_onLayer(kAutoresizingMask, currentLayer);

Context

当我们输入插件定制的命令时,Sketch会去寻找改命令对应的实现函数, 并传入context变量。context 包含以下变量:

  • command: MSPluginCommand对象,代表当前执行的命令
  • document: MSDocument 对象 ,当前的文档
  • plugin: MSPluginBundle 对象,当前的插件bundle,里面包含当前运行的脚本
  • scriptPath: NSString 当前执行脚本的绝对路径
  • scriptURL: 当前执行脚本的绝对路径,跟 scriptPath不同的是它是个 NSURL 对象
  • selection,一个 NSArray 对象,包含了当前选择的所有图层。数组中的每一个元素都是 MSLayer 对象

// context的到的信息

var app = NSApplication.sharedApplication(),
    selection,
    plugin,
    command,
    doc,
    page,
    artboards,
    selectedArtboard;

function initContext(context) {
    doc = context.document,
        plugin = context.plugin,
        command = context.command,
        page = doc.currentPage(),
        artboards = page.artboards(),  
        selectedArtboard = page.currentArtboard(),  // 当前被选择的画板
        selection = context.selection,   // 被选择的图层
        
  for (var i=0; i<selection.count(); i++) {
    var layer = selection[i]
    log('layer ' + layer.name + ' is selected.')
  }
}
 
command:

MSPluginCommand对象,代表插件中单个命令,可以用来访问当前执行的命令,也可以用来在图层中存储自己的扩展元数据。

valueForKey:onLayer
setValue:forKey:onLayer:

在图层中存取的拓展数据,也可以在不同插件中共享。

valueForKey:onLayer:forPluginIdentifier:
setValue:forKey:onLayer:forPluginIdentifier:
document
showMessage:(NSString)message // 在sketch底部弹出信息,我经常用来打日志。。。哭

selection

当前选择的document下的一组被选择的MSLayers对象。
如果当前只选了一个图层,可以这样获取:

var currentLayer = (selection.count() > 0) ? selection[0] : undefined

编译环境

运行和debug

主要依赖打log.用Console.app过滤日志查看,过滤标签可以是你写的插件的名字,也可以用“sketch”过滤,但是这样会得到所有命令的执行日志。

log("The value of count is:" + count)

或者在代码中用视图控件显示,好处就是不用不用开第三方app.比如:

alert, [doc showMessage]showMessage("message")

Sketch-Header

有人dump出来的Sketch的头文件。信息量非常丰富哈哈~
https://github.com/abynim/Sketch-Headers

例子:

获取画板的所有layer:

以这个设计图为例
https://github.com/bouchenoiremarc/Sketch-Constraints/blob/master/Example.sketch

var artboardEnumerator = artboards.objectEnumerator();
while (artboard = artboardEnumerator.nextObject()) {
    //var layers = artboard.layers().array();
    //var layers = artboard.children();
    log(layers);
}
//  layers返回画布第一层的 subLayer
//var layers = artboard.layers().array();
/**
 *
 "<MSLayerGroup: 0x6180001d3b00> Group (741958C5-E1CE-468F-9AB2-E853C0799423)",
 "<MSShapeGroup: 0x7f82e052c260> Camera (7E5D9F7A-2C5A-4223-AD83-8C5F340AC5EF)",
 "<MSShapeGroup: 0x7f82e052de30> Control Center Grabber (936460F8-5773-4F47-89C2-C4BD246C63EC)",
 "<MSLayerGroup: 0x6180001d3bf0> Slide to unlock (A240F642-0036-4629-A365-D0F537A744F8)",
 "<MSTextLayer: 0x7f82e052df40> Date (9BE84955-A291-431D-8771-C36D51743FDD)",
 "<MSTextLayer: 0x7f82e052e080> Time (FCF1C9FD-D6FD-4FFD-9B5F-B9D2635584BB)",
 "<MSLayerGroup: 0x6180001d3ce0> Charge (6F95F078-56BC-4FDA-A319-DE0FF8C50E13)",
 "<MSShapeGroup: 0x7f82e052e1c0> Notification Center Grabber (75CA34DC-7FA7-4D5B-96AB-922C23F74DC5)",
 "<MSShapeGroup: 0x7f82e052e2d0> Wifi (38D4CE87-0826-405C-B13C-D30A6EE16437)",
 "<MSLayerGroup: 0x6180001d3dd0> Signal (5B08C199-0398-45CC-9905-A8B16EFB5B71)",
 "<MSTextLayer: 0x7f82e052e3e0> @constraints (7E04B443-1D85-48FB-B4C6-2334FE7A6408)"
 **/


//     当前画板的全部图层
//     var layers = artboard.children();

/**
 * (
 "<MSBitmapLayer: 0x7f82e0761c20> Wallpaper (83A6D488-6FE4-46A9-8CCF-8DBB12C1F845)",
 "<MSLayerGroup: 0x6180001d3b00> Group (741958C5-E1CE-468F-9AB2-E853C0799423)",
 "<MSRectangleShape: 0x610000193ce0> Path (D428D7A1-042A-4700-9D59-3CC601B79047)",
 "<MSShapePathLayer: 0x610000364c80> Path (A98F99AE-2B01-49F9-B8AB-41B9913581D4)",
 "<MSShapePathLayer: 0x610000364d40> Path (0B844654-8140-4A20-B090-3B41ACBBBF25)",
 "<MSOvalShape: 0x610000364e00> Oval (0001F0C5-032D-47C7-BD66-41262D08D9AB)",
 "<MSRectangleShape: 0x610000193db0> Rectangle (7930B492-435C-41EF-B802-7B36297D4A67)",
 "<MSShapeGroup: 0x7f82e052c260> Camera (7E5D9F7A-2C5A-4223-AD83-8C5F340AC5EF)",
 "<MSRectangleShape: 0x610000193c10> Path (C66C2797-E56B-4D69-9D25-B68614EEE93C)",
 "<MSShapeGroup: 0x7f82e052de30> Control Center Grabber (936460F8-5773-4F47-89C2-C4BD246C63EC)",
 "<MSTextLayer: 0x7f82e0761a20> Text (8D49531C-EE6F-44DB-BD5B-6CB1FC6BC8E5)",
 "<MSShapePathLayer: 0x600000361800> Path (7B83C7E2-AA83-4DA4-81A5-F20AE9499B99)",
 "<MSShapeGroup: 0x7f82e07613d0> Arrow (8A5109A2-945D-4D12-BF08-9026FE97D639)",
 "<MSLayerGroup: 0x6180001d3bf0> Slide to unlock (A240F642-0036-4629-A365-D0F537A744F8)",
 "<MSTextLayer: 0x7f82e052df40> Date (9BE84955-A291-431D-8771-C36D51743FDD)",
 "<MSTextLayer: 0x7f82e052e080> Time (FCF1C9FD-D6FD-4FFD-9B5F-B9D2635584BB)",
 "<MSShapePathLayer: 0x61800017c500> Path (D46E9CEA-1918-4070-8247-55D88D2F6A4F)",
 "<MSShapePathLayer: 0x61800017c5c0> Path (23F3EAA0-5970-4746-BB42-3E49B5C346A5)",
 "<MSShapeGroup: 0x7f82e075d200> Battery (F05E72B0-160F-4997-AB7F-B10F7FB6B9B8)",
 "<MSRectangleShape: 0x618000191d30> Path (8A682D4A-34CE-44DA-A986-BFAAFA448E48)",
 "<MSShapeGroup: 0x7f82e075fac0> Fill (3AF6A505-68FE-4BAD-9BA5-4C859D8548F6)",
 "<MSShapePathLayer: 0x61800017c680> Path (3A64AA1C-E554-4B86-A41D-67323D4B04D1)",
 "<MSShapeGroup: 0x7f82e075fbd0> + (BA404D3E-327F-4618-81A2-4371F04482CF)",
 "<MSLayerGroup: 0x6180001d3ce0> Charge (6F95F078-56BC-4FDA-A319-DE0FF8C50E13)",
 "<MSRectangleShape: 0x6100001938d0> Path (BE0B6A98-1C60-4DCB-B464-526E4FAC6950)",
 "<MSShapeGroup: 0x7f82e052e1c0> Notification Center Grabber (75CA34DC-7FA7-4D5B-96AB-922C23F74DC5)",
 "<MSShapePathLayer: 0x610000364500> Path (332FBE18-C807-4C6E-938D-62178B9F620E)",
 "<MSShapePathLayer: 0x610000364200> Path (2E267A2D-E7E0-44DB-91C1-4D79B1FE0FD8)",
 "<MSShapePathLayer: 0x610000364b00> Path (BF7FAE10-2DC1-4ADF-B3D0-A851AAB969C7)",
 "<MSShapeGroup: 0x7f82e052e2d0> Wifi (38D4CE87-0826-405C-B13C-D30A6EE16437)",
 "<MSOvalShape: 0x61800017c740> Path (64D27B50-F968-4E57-B68E-64736A85AC85)",
 "<MSShapeGroup: 0x7f82e075d910> Full (453FF4A7-D7D3-4A11-BE26-77C86E5F4016)",
 "<MSOvalShape: 0x61800017c800> Path (0DD8FB65-2650-44BE-B4C6-E5CB9A76E59E)",
 "<MSShapeGroup: 0x7f82e075da20> Full (9AD329E6-7ED9-48AB-946A-991EEF1E1170)",
 "<MSOvalShape: 0x61800017c8c0> Path (4EA334DD-A423-4C39-B8A2-5F3656A95E73)",
 "<MSShapeGroup: 0x7f82e075ced0> Full (4E2540EB-BCB8-41CB-9338-9146DC678E71)",
 "<MSShapePathLayer: 0x61800017c980> Path (795A2891-D154-4E52-81F6-7FD79A9A4308)",
 "<MSShapePathLayer: 0x61800017ca40> Path (F1D41D13-370E-4326-823F-A4AAABC80047)",
 "<MSShapeGroup: 0x7f82e075cfe0> Empty (1002B7B5-9CD2-463E-B2A4-4883174074C2)",
 "<MSShapePathLayer: 0x61800017cb00> Path (5577CC1A-9C95-45A7-89E9-AB098B6D0329)",
 "<MSShapePathLayer: 0x61800017cbc0> Path (7628098C-32E7-46E7-A9F6-CBF1E2654653)",
 "<MSShapeGroup: 0x7f82e075d0f0> Empty (86BBDD79-5F5D-4559-8958-002EAF3A353B)",
 "<MSLayerGroup: 0x6180001d3dd0> Signal (5B08C199-0398-45CC-9905-A8B16EFB5B71)",
 "<MSTextLayer: 0x7f82e052e3e0> @constraints (7E04B443-1D85-48FB-B4C6-2334FE7A6408)",
 "<MSArtboardGroup: 0x7f82e074a500> iPhone 6 (8BCE4790-108A-45B3-9F4B-AE4292A8CF27)"
 )
 */

MSArtboardGroup:画板
MSShapeGroup:组里的图层都是shape ,比如wifi
MSLayerGroup:比如局域网信号

图层基类 :
MSLayer
http://developer.sketchapp.com/reference/MSLayer/
https://github.com/abynim/Sketch-Headers/blob/master/Headers/MSLayer.h

文本层
MSTextLayer
https://github.com/abynim/Sketch-Headers/blob/master/Headers/MSTextLayer.h

图形层:
https://github.com/abynim/Sketch-Headers/blob/master/Headers/MSShapePathLayer.h

MSOvalShape:
MSBitmapLayer:
http://developer.sketchapp.com/reference/MSBitmapLayer/
https://github.com/abynim/Sketch-Headers/blob/master/Headers/MSBitmapLayer.h

实现layer的autoResize属性

1.1 获取layer的parentGroup,parent对象可能是MSPage、MSArtboardGroup或MSLayerGroup
1.2 获得自己的frame,手动计算缩放比例,控制。顺便说一句,Sketch有个残暴的接口:

        layer.frame().scaleBy(radio);

Action

利用Sketch已经实现的一些响应接口,插件少写代码,得到的效果更好。

  sendAction: function (commandToPerform) {
      try {
          // target 指定为nil,app会去寻找,响应这个消息的对象。
          [NSApp sendAction:commandToPerform to:nil from:context.document];
      } catch(e) {
          log(e)
      }
  },

在Sketch-Header中可以看到到,Sketch可以响应的 Action,比如:

 MSAlignLayersLeftAction.h      
 - (void)alignLayersLeft:(id)arg1;
MSAlignLayersRightAction.h
- (void)alignLayersRight:(id)arg1;

这些头文件,都继承了MSBaseAlignLayersAction。MSBaseAlignLayersAction继承MSBaseAction。MSBaseAction继承了NSResponder 0 0呵呵哈。

图层中存取拓展数据


var doc = context.document;
var selection = context.selection;
var command = context.command;

var currentLayer = (selection.count() > 0) ? selection[0] : false;

var kAutoresizingMask = "kAutoresizingMask";
var content = {
    kAutoresizingFlexibleLeftMargin : "AutoresizingFlexibleLeftMargin",
    kAutoresizingFlexibleRightMargin : "AutoresizingFlexibleRightMargin",
    kAutoresizingFlexibleTopMargin : "AutoresizingFlexibleTopMargin",
    kAutoresizingFlexibleBottomMargin : "kAutoresizingFlexibleTopMargin",
    kAutoresizingFlexibleWidth : "AutoresizingFlexibleWidth",
    kAutoresizingFlexibleHeight : "kAutoresizingFlexibleHeight",
};

var formattedContent = JSON.stringify(content, null, "\t");
command.setValue_forKey_onLayer(formattedContent, kAutoresizingMask, currentLayer);

var constraintsForLayer = command.valueForKey_onLayer(kAutoresizingMask, currentLayer);
log(constraintsForLayer);
log(JSON.stringify(constraintsForLayer, null, "\t"));

附上本周写的个简单插件https://github.com/sueLan/Artboard-Mold-For-Sketch

    原文作者:蓝新
    原文地址: https://www.jianshu.com/p/f6e764390502
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞