Arvids Blog

Thoughts on programming and more

Automatically exporting assets from Sketch into Android Studio

Matt Zanchelli wrote a blog post about automatically exporting assets from Sketch into Xcode, unfortunately this method can only be used with Xcode projects, but fortunately we have Gradle.

I ported this technique to use Gradle an achieve the same for Android Studio projects.

Installing Sketchtool

You have to install sketchtool first, it’s a tool by Bohemian Coding (the makers of Sketch), to work with .sketch tools on the command line.
Download the Sketchtool and move the content of the directory into /usr/bin.

Alternatively, you can use this shell script, which basically does the same for you:

curl -O http://sketchtool.bohemiancoding.com/sketchtool-latest.zip;\
unzip sketchtool-latest.zip;\
sudo cp sketchtool/sketchtool /usr/bin/sketchtool;\
sudo cp -R sketchtool/sketchtool\ resources.bundle/ /usr/bin/sketchtool\ resources.bundle/;\
rm -r sketchtool/;\
rm sketchtool-latest.zip;

Screencast

Setting up the project

To organize the Sketch files, I created a subfolder in the root directory of the project and moved the AppIcon.sketch file into it. To create the image files of from the artboards in the file, we need a shell script. Create a AppIcon.sh file and copy the code below into the file.

#!/bin/sh

/usr/bin/sketchtool export artboards AppIcon.sketch

mv HDPI.png ../app/src/main/res/drawable-hdpi/ic_launcher.png
mv XHDPI.png ../app/src/main/res/drawable-xhdpi/ic_launcher.png
mv XXHDPI.png ../app/src/main/res/drawable-xxhdpi/ic_launcher.png
mv XXXHDPI.png ../app/src/main/res/drawable-xxxhdpi/ic_launcher.png

Modifying the build.gradle

This script has to be executed before every compilation of the project, to achieve this we have to modify our build.gradle file, by appending the following:

task copySketch(type:Exec) {
 workingDir '../Graphics Resources'
 commandLine './AppIcon.sh'
}
preBuild.dependsOn copySketch

It assumes, you use the same structure as described above. If you don’t, adjust the paths accordingly (the default directory, is the directory where the build.gradle lives in).

Sample Project

You can download the sample project, or visit the Github repository.