Export ImageSets @2x and @3x sizes from Sketch to Xcode

675 Views Asked by At

Used following code to export the images, but as i am specifying file size as 40 80 120, for every image it is creating with same sizes. Should consider default image size and should create @2x and @3x images.

function exportIcons()
{

    sketchtool export slices "$SKETCH_FILE" \
        --output="$ICONS_DIR" \
        --formats="png" \
    # create assets to XCode
    cd $ICONS_DIR

    for file in *.png
        do

        filename=${file%%@*}



fname=${filename:0:${filename}-4}

        # create imageset file
        assets_name="$fname".imageset
        icon_assets_dir="$IMAGES_ASSETS_DIR"/"$assets_name"


png="$fname"".png"
twopng="$fname""@2x.png"
threepng="$fname""@3x.png"

height=${sips -g pixelHeight "$file"}

printf "height >> $height  \n"

cp -p "$filename" "$png"
  sips -Z 40 "$png"

cp -p "$filename" "$twopng"
  sips -Z 80 "$twopng"

cp -p "$filename" "$threepng"
  sips -Z 120 "$threepng"

cat << EOF > Contents.json
{
"images" : [
{
"idiom" : "iphone",
"filename" : "$png",
"scale" : "1x"
},{
"idiom" : "iphone",
"filename" : "$twopng",
"scale" : "2x"
},
{
"idiom" : "iphone",
"filename" : "$threepng",
"scale" : "3x"
}
],
"info" : {
"version" : 1,
"author" : "xcode"
}
}
EOF


        # copy imageset file to XCode
        mkdir -p "$icon_assets_dir"

        /bin/cp "$png" "$icon_assets_dir"/"$png"
        /bin/cp "$twopng" "$icon_assets_dir"/"$twopng"
        /bin/cp "$threepng" "$icon_assets_dir"/"$threepng"

        /bin/cp Contents.json "$icon_assets_dir"/Contents.json
    done

    cd $PROJECT_DIR

    # remove unused files
    rm -rf "$ICONS_DIR"
}
1

There are 1 best solutions below

0
On

Here is the solution I found to generate @2x and @3x based on default image:

# grab the identify string, make sure it succeeded
IMG_CHARS=$(identify "${file}" 2> /dev/null) || die "${file} is not a proper image"

# grab width and height
IMG_CHARS=$(echo "${IMG_CHARS}" | sed -n 's/\(^.*\)\ \([0-9]*\)x\([0-9]*\)\ \(.*$\)/\2 \3/p')

width=$(echo "${IMG_CHARS}" | awk '{print $1}')
height=$(echo "${IMG_CHARS}" | awk '{print $2}')

cp -p "$filename" "$png"
  sips -Z "$(($width * 1))" "$(($height * 1))" "$png"

cp -p "$filename" "$twopng"
  sips -Z "$(($width * 2))" "$(($height * 2))" "$twopng"

cp -p "$filename" "$threepng"
  sips -Z "$(($width * 3))" "$(($height * 3))" "$threepng"