Skip to content

Instantly share code, notes, and snippets.

@azhawkes
Created December 20, 2012 19:01
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save azhawkes/4347761 to your computer and use it in GitHub Desktop.
Save azhawkes/4347761 to your computer and use it in GitHub Desktop.
Simple Java/SWT class for image sprites. Quickly slice up a larger image into smaller ones, while preserving alpha transparency. Most of the existing examples out there don't handle alphas properly.
package com.andyhawkes.gists;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.ImageData;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.widgets.Display;
/**
* Simple class that demonstrates how to slice up regions of a sprite image in SWT, while preserving
* alpha transparency. There are shorter ways to do this if you don't care about alpha transparency.
*/
public class SwtImageSprite {
private Image sprite;
public SwtImageSprite(Image sprite) {
this.sprite = sprite;
}
public Image loadImageFromRegion(Rectangle region) {
ImageData data = new ImageData(region.width, region.height, sprite.getImageData().depth, sprite.getImageData().palette);
int[] pixels = new int[region.width];
byte[] alphas = new byte[region.width];
for (int y = 0; y < region.height; y++) {
sprite.getImageData().getAlphas(region.x, region.y + y, region.width, alphas, 0);
sprite.getImageData().getPixels(region.x, region.y + y, region.width, pixels, 0);
data.setPixels(0, y, region.width, pixels, 0);
data.setAlphas(0, y, region.width, alphas, 0);
}
return new Image(Display.getCurrent(), data);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment