Skip to content

Instantly share code, notes, and snippets.

@rijieli
Last active August 17, 2021 05:52
Show Gist options
  • Save rijieli/03f2144536330a01fd304e68e0dc92f8 to your computer and use it in GitHub Desktop.
Save rijieli/03f2144536330a01fd304e68e0dc92f8 to your computer and use it in GitHub Desktop.
This Script convert Sketch gradient to CALayer Swift Code. Open Sketch, select one layer, press control + shift + K paste code to run.
console.log('Select Layer Then Run Script.');
var sketch = require('sketch');
var UI = require('sketch/ui');
var document = sketch.getSelectedDocument();
var selectedLayers = document.selectedLayers;
var selectedCount = selectedLayers.length;
function hexToRGBA(hex) {
var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
return result ? {
r: parseInt(result[1], 16),
g: parseInt(result[2], 16),
b: parseInt(result[3], 16),
a: parseInt(result[4], 16)
} : null;
}
let precesion = 10000
function parseGradient(layerGradient) {
let colorItems = ""
let locationArray = ""
layerGradient.stops.forEach(elm => {
let rgbaColor = hexToRGBA(elm.color)
colorItems += `UIColor(red: ${rgbaColor.r}/255.0, green: ${rgbaColor.g}/255.0, blue: ${rgbaColor.b}/255.0, alpha: ${rgbaColor.a}/255.0), `
locationArray += `${Math.round(elm.position*precesion)/precesion}, `
});
var codeTemplate = `
import Foundation
import UIKit
class LinearGradientLayer: CALayer {
required override init() {
super.init()
needsDisplayOnBoundsChange = true
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
required override init(layer: Any) {
super.init(layer: layer)
}
let colors = [${colorItems}].map(\{ \$0.cgColor \})
override func draw(in ctx: CGContext) {
ctx.saveGState()
let colorSpace = CGColorSpaceCreateDeviceRGB()
let locations: [CGFloat] = [${locationArray}]
let gradient = CGGradient(colorsSpace: colorSpace, colors: colors as CFArray, locations: locations)!
ctx.drawLinearGradient(gradient, start: CGPoint(x: ${Math.round(layerGradient.from.x*precesion)/precesion}*bounds.width, y: ${Math.round(layerGradient.from.y*precesion)/precesion}*bounds.height), end: CGPoint(x: ${Math.round(layerGradient.to.x*precesion)/precesion}*bounds.width, y: ${Math.round(layerGradient.to.y*precesion)/precesion}*bounds.height), options: [.drawsBeforeStartLocation, .drawsAfterEndLocation])
}
}
`;
return codeTemplate
}
if (selectedCount === 0) {
UI.alert('No layers are selected', 'Select one gradient filled layer and rerun.')
} else {
selectedLayers.forEach(function (layer, i) {
console.log((i + 1) + '. ' + layer.name);
let layerGradient = layer.style.fills[0].gradient;
console.log(layerGradient)
UI.getInputFromUser(
"Convert Result",
{
initialValue: parseGradient(layerGradient),
numberOfLines: 12
},
(err, value) => {
if (err) {
// most likely the user canceled the input
return;
}
}
);
});
}
@rijieli
Copy link
Author

rijieli commented Aug 17, 2021

This script convert Sketch gradient layer to CALayer. Insert this layer by view.layer.insertSublayer(gradientLayer, at: 0).

Select a layer which contains one gradient fill, then press control + shift + K, paste code below and run. you will see:

Convert Result

And on iPhone it looks like:

On Real Device

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment