Sketch Plugin: How to programmatically make a layer exportable?

1.2k views Asked by At

So, in Sketch, you can mark a layer/group as exportable.

enter image description here

And then the layer/group can be exported as .png/.svg/.pdf etc. I was trying to make a Sketch Plugin recently, where I need to mark a layer/group as exportable from code. A layer in code is represented using MSLayer and group is MSLayerGroup. The sketch documentation is not mature enough yet, so I used ClassDump to extract all the headers that has been used in the app. I have been looking for a method that might seem to do my job, but it has been days and am still out of luck. Can anybody please help me out in this regard?

1

There are 1 answers

1
Nickolas On

Sketch supports slice and export to image. You can use - (void)saveArtboardOrSlice:(id)arg1 toFile:(id)arg2; method of MSDocument.

This is almost how to do it.

var loopLayerChildren = [[layerToExport children] objectEnumerator],
    rect = [MSSliceTrimming trimmedRectForSlice:layer],
    useSliceLayer = false,
    exportFilePath,
    slice;

// Check for MSSliceLayer and overwrite the rect if present
while (layerChild = [loopLayerChildren nextObject]) {
    if ([layerChild class] == 'MSSliceLayer') {
        rect  = [MSSliceTrimming trimmedRectForSlice:layerChild];
        useSliceLayer = true;
    }
}

slice = [MSExportRequest requestWithRect:rect scale:1];

if (!useSliceLayer) {
    slice.shouldTrim = true;
}

// export to image file
[(this.document) saveArtboardOrSlice: slice toFile:exportFilePath];

Reference from @GeertWill's sketch-to-xcode-assets-catalog plugin.