Photoshop Script to Create Grid

I learned a little about the (surprisingly) simple Photoshop Javascript API today, and wrote a little script to do what had always driven me nuts before. :smiley:

/*

<javascriptresource>
	<name>Create Grid</name>
	<about>Create a layer that is solid minus a grid of a certain value repeating both horizontally and vertically.</about>
	<enableinfo>true</enableinfo>
</javascriptresource>

*/

// Warning: Don't change this
const GRID_HORIZONTAL = 1
const GRID_VERTICAL = 2
const GRID_BOTH = GRID_HORIZONTAL | GRID_VERTICAL

// But do change this.
const GRID_SIZE = 72
const GRID_LINES = GRID_BOTH
const GRID_OPACITY = 40.00
const GRID_LAYER_NAME = "Grid"

// And don't change anything below this
function selectGrid(document, size) {
	document.selection.selectAll()
	
	// Cut vertical lines
	if ((GRID_LINES & GRID_VERTICAL) == GRID_VERTICAL) {
		for (var i=0; size*i+1 <= document.width; i++) {
			document.selection.select([
				[size*i, 0],
				[size*i+1, 0],
				[size*i+1, document.height],
				[size*i, document.height],
				[size*i, 0]
			], SelectionType.DIMINISH)
		}
	}
	
	// Cut horizontal lines
	if ((GRID_LINES & GRID_HORIZONTAL) == GRID_HORIZONTAL) {
		for (var i=0; size*i+1 <= document.height; i++) {
			document.selection.select([
				[0, size*i],
				[0, size*i+1],
				[document.width, size*i+1],
				[document.width, size*i],
				[0, size*i]
			], SelectionType.DIMINISH)
		}
	}
}

function createGrid() {
	// Use pixels
	var originalUnits = preferences.rulerUnits
	preferences.rulerUnits = Units.PIXELS
	
	var docRef = app.activeDocument
	var gridLayer = docRef.artLayers.add()
	
	docRef.activeLayer = gridLayer
	gridLayer.name = GRID_LAYER_NAME
	gridLayer.opacity = GRID_OPACITY
	
	selectGrid(docRef, GRID_SIZE)
	docRef.selection.fill(app.foregroundColor)
	docRef.selection.deselect()
	
	// Clean the memory
	docRef = null
	gridLayer = null
	
	// Reset the preferences
	app.preferences.rulerUnits = originalUnits
}

// Start the script
if (app.documents.length > 0) {
	createGrid()
} else {
	alert("You must already have an active document.");
}

Put this in the Photoshop CS3 folder/Presets/Scripts, and then restart PS; it should be available through the File -> Scripts menu as “Create Grid.” Alternatively, just place it wherever you like, and use the Browse menu item under the Scripts menu to load it manually.

I don’t think there’s any way to launch a (pretty) dialog through the API, so the preferences are currently just in the script; hopefully they’re relatively intuitive. It just creates a grid on the top of your file of the specified size.

This is useful because unlike the built-in grid which doesn’t actually have pixels that it uses, this does. So, the built-in grid has funky snap issues where the aliasing can quickly get ugly.

I got the idea from some grid-focused designer a while back … can’t seem to remember his name anymore, though.